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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/BranchFullNameUtils.java
gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/BranchFullNameUtils.java
package com.virtuslab.gitcore.impl.jgit; import org.eclipse.jgit.lib.Constants; final class BranchFullNameUtils { private BranchFullNameUtils() {} static String getLocalBranchFullName(String localBranchName) { return Constants.R_HEADS + localBranchName; } static String getRemoteBranchName(String remoteName, String remoteBranchShortName) { return remoteName + "/" + remoteBranchShortName; } static String getRemoteBranchFullName(String remoteName, String remoteBranchShortName) { return Constants.R_REMOTES + getRemoteBranchName(remoteName, remoteBranchShortName); } }
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/GitCoreCommitHash.java
gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreCommitHash.java
package com.virtuslab.gitcore.impl.jgit; import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.jgit.lib.ObjectId; import com.virtuslab.gitcore.api.IGitCoreCommitHash; public final class GitCoreCommitHash extends GitCoreObjectHash implements IGitCoreCommitHash { private GitCoreCommitHash(ObjectId objectId) { super(objectId); } public static GitCoreCommitHash toGitCoreCommitHash(ObjectId objectId) { return new GitCoreCommitHash(objectId); } public static @Nullable IGitCoreCommitHash toGitCoreCommitHashOption(ObjectId objectId) { return objectId.equals(ObjectId.zeroId()) ? null : toGitCoreCommitHash(objectId); } @Override public String toString() { return "<commit " + 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/GitCoreLocalBranchSnapshot.java
gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreLocalBranchSnapshot.java
package com.virtuslab.gitcore.impl.jgit; import static com.virtuslab.gitcore.impl.jgit.BranchFullNameUtils.getLocalBranchFullName; import io.vavr.collection.List; import org.eclipse.jgit.annotations.Nullable; import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot; import com.virtuslab.gitcore.api.IGitCoreReflogEntry; import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot; public class GitCoreLocalBranchSnapshot extends BaseGitCoreBranchSnapshot implements IGitCoreLocalBranchSnapshot { private @Nullable final IGitCoreRemoteBranchSnapshot remoteBranch; public GitCoreLocalBranchSnapshot( String shortBranchName, GitCoreCommit pointedCommit, List<IGitCoreReflogEntry> reflog, @Nullable IGitCoreRemoteBranchSnapshot remoteBranch) { super(shortBranchName, pointedCommit, reflog); this.remoteBranch = remoteBranch; } @Override public String getName() { return shortName; } @Override public String getFullName() { return getLocalBranchFullName(shortName); } @Override public String getBranchTypeString(boolean capitalized) { return capitalized ? "Local" : "local"; } @Override public @Nullable IGitCoreRemoteBranchSnapshot getRemoteTrackingBranch() { return remoteBranch; } }
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/GitCoreCommit.java
gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreCommit.java
package com.virtuslab.gitcore.impl.jgit; import java.time.Instant; import lombok.Getter; import lombok.experimental.ExtensionMethod; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.aliasing.qual.NonLeaked; import org.eclipse.jgit.revwalk.RevCommit; import com.virtuslab.gitcore.api.IGitCoreCommit; import com.virtuslab.gitcore.api.IGitCoreCommitHash; import com.virtuslab.gitcore.api.IGitCoreTreeHash; @ExtensionMethod({GitCoreCommitHash.class, GitCoreTreeHash.class}) @Getter public class GitCoreCommit implements IGitCoreCommit { private final String shortMessage; private final String fullMessage; private final Instant commitTime; private final IGitCoreCommitHash hash; private final IGitCoreTreeHash treeHash; public GitCoreCommit(@NonLeaked RevCommit commit) { // We do NOT want to use org.eclipse.jgit.revwalk.RevCommit#getShortMessage here // as it returns the commit *subject*, which is the part of the commit message until the first empty line // (or whole message, if no such empty line is present). // This might include multiple lines from the original commit message, glued up together with spaces. // Let's just instead include the first line of the commit message, no exceptions. this.shortMessage = commit.getFullMessage().lines().findFirst().orElse(""); this.fullMessage = commit.getFullMessage(); this.commitTime = Instant.ofEpochSecond(commit.getCommitTime()); this.hash = commit.getId().toGitCoreCommitHash(); this.treeHash = commit.getTree().getId().toGitCoreTreeHash(); } @Override public String toString() { return hash.getShortHashString() + " ('" + shortMessage + "')"; } @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/branchLayout/impl/src/test/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutFileReaderTestSuite.java
branchLayout/impl/src/test/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutFileReaderTestSuite.java
package com.virtuslab.branchlayout.impl.readwrite; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.stream.Collectors; import io.vavr.collection.List; import lombok.SneakyThrows; import lombok.val; import org.junit.jupiter.api.Test; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutException; public class BranchLayoutFileReaderTestSuite { public static InputStream getInputStreamFromLines(List<String> lines) { return new ByteArrayInputStream( lines.collect(Collectors.joining(System.lineSeparator())) .getBytes()); } @Test @SneakyThrows public void read_givenCorrectFile_reads() { // given val linesToReturn = List.of(" ", "A", " B", "C", ""); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayout branchLayout = new BranchLayoutReader().read(linesStream); // then assertNotNull(branchLayout.getEntryByName("A")); assertNotNull(branchLayout.getEntryByName("B")); assertNotNull(branchLayout.getEntryByName("C")); assertEquals(2, branchLayout.getRootEntries().size()); val a = branchLayout.getRootEntries().get(0); val b = a.getChildren().get(0); val c = branchLayout.getRootEntries().get(0); assertSame(a, b.getParent()); assertNull(a.getParent()); assertNull(c.getParent()); } @Test @SneakyThrows public void read_givenCorrectFileWithRootsOnly_reads() { // given List<String> linesToReturn = List.of("A", " ", "B"); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayout branchLayout = new BranchLayoutReader().read(linesStream); // then assertNotNull(branchLayout.getEntryByName("A")); assertNotNull(branchLayout.getEntryByName("B")); assertEquals(2, branchLayout.getRootEntries().size()); } @Test @SneakyThrows public void read_givenEmptyFile_reads() { // given List<String> linesToReturn = List.empty(); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayout branchLayout = new BranchLayoutReader().read(linesStream); // then no exception thrown assertEquals(0, branchLayout.getRootEntries().size()); } @Test public void read_givenFileWithIndentedFirstEntry_throwsException() { // given List<String> linesToReturn = List.of(" ", " ", " A", " B", " "); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayoutException exception = assertThrows(BranchLayoutException.class, () -> new BranchLayoutReader().read(linesStream)); // then int i = exception.getErrorLine(); assertEquals(3, i); } @Test public void read_givenFileWithIndentWidthNotAMultiplicityOfLevelWidth_throwsException() { // given List<String> linesToReturn = List.of("A", " ", " B", " C"); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayoutException exception = assertThrows(BranchLayoutException.class, () -> new BranchLayoutReader().read(linesStream)); System.out.println(exception.getMessage()); // then int i = exception.getErrorLine(); assertEquals(4, i); } @Test public void read_givenFileWithChildIndentGreaterThanOneToParent_throwsException() { // given List<String> linesToReturn = List.of(" ", "A", "", " B", " C"); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayoutException exception = assertThrows(BranchLayoutException.class, () -> new BranchLayoutReader().read(linesStream)); // then int i = exception.getErrorLine(); assertEquals(5, i); } @Test public void read_givenFileWithDifferentIndentCharacters_throwsException() { // given List<String> linesToReturn = List.of("A", " B", "\tC"); val linesStream = getInputStreamFromLines(linesToReturn); // when BranchLayoutException exception = assertThrows(BranchLayoutException.class, () -> new BranchLayoutReader().read(linesStream)); // then int i = exception.getErrorLine(); assertEquals(3, i); } }
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/branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutReader.java
branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutReader.java
package com.virtuslab.branchlayout.impl.readwrite; import java.io.IOException; import java.io.InputStream; import io.vavr.Tuple2; import io.vavr.collection.Array; import io.vavr.collection.List; import lombok.CustomLog; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.index.qual.GTENegativeOne; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutEntry; import com.virtuslab.branchlayout.api.BranchLayoutException; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader; import com.virtuslab.branchlayout.api.readwrite.IndentSpec; import com.virtuslab.qual.guieffect.IgnoreUIThreadUnsafeCalls; @ExtensionMethod(BranchLayoutFileUtils.class) @CustomLog public class BranchLayoutReader implements IBranchLayoutReader { @IgnoreUIThreadUnsafeCalls("java.io.InputStream.readAllBytes()") @Override public BranchLayout read(InputStream inputStream) throws BranchLayoutException { List<BranchLayoutEntry> roots = List.empty(); try { List<String> lines = List.ofAll(new String(inputStream.readAllBytes()).lines()); IndentSpec indentSpec = lines.deriveIndentSpec(); LOG.debug(() -> "Entering: Reading branch layout with indent character ASCII " + "code = ${(int)indentSpec.getIndentCharacter()} and indent width = ${indentSpec.getIndentWidth()}"); LOG.debug(() -> "${lines.length()} line(s) found"); List<String> linesWithoutBlank = lines.reject(String::isBlank); if (!linesWithoutBlank.isEmpty()) { Array<Tuple2<Integer, Integer>> lineIndexToIndentLevelAndParentLineIndex = parseToArrayRepresentation(indentSpec, lines); LOG.debug(() -> "lineIndexToIndentLevelAndParentLineIndex = ${lineIndexToIndentLevelAndParentLineIndex}"); roots = buildEntriesStructure(linesWithoutBlank, lineIndexToIndentLevelAndParentLineIndex, /* parentLineIndex */ -1); } else { LOG.debug("Branch layout file is empty"); } } catch (IOException e) { throw new BranchLayoutException("Unable to read branch layout file", e); } return new BranchLayout(roots); } /** * @param lines * list of lines read from branch layout file * @param lineIndexToParentLineIndex * as it says ({@code lines} metadata containing structure, see {@link #parseToArrayRepresentation}) * @param parentLineIndex * index of the line whose children are to be built * * @return list of entries with recursively built lists of children */ @SuppressWarnings("index:argument") private List<BranchLayoutEntry> buildEntriesStructure( List<String> lines, Array<Tuple2<Integer, Integer>> lineIndexToParentLineIndex, @GTENegativeOne int parentLineIndex) { return lineIndexToParentLineIndex .zipWithIndex() .filter(t -> t._1()._2() == parentLineIndex) .map(t -> createEntry(lines.get(t._2()), buildEntriesStructure(lines, lineIndexToParentLineIndex, t._2()))) .toList(); } /** * Parses line to {@link BranchLayoutEntry#BranchLayoutEntry} arguments and creates an * entry with the specified {@code children}. */ private BranchLayoutEntry createEntry(String line, List<BranchLayoutEntry> children) { LOG.debug(() -> "Entering: line = '${line}', children = ${children}"); String trimmedLine = line.trim(); String branchName; String customAnnotation; int indexOfSpace = trimmedLine.indexOf(' '); if (indexOfSpace > -1) { branchName = trimmedLine.substring(0, indexOfSpace); customAnnotation = trimmedLine.substring(indexOfSpace + 1).trim(); } else { branchName = trimmedLine; customAnnotation = null; } val result = new BranchLayoutEntry(branchName, customAnnotation, children); LOG.debug(() -> "Created ${result}"); return result; } /** * @return an array containing the indent level and parent entry describing line index which indices correspond to * provided {@code lines} indices. It may be understood as a helper metadata needed to build entries structure */ private Array<Tuple2<Integer, Integer>> parseToArrayRepresentation(IndentSpec indentSpec, List<String> lines) throws BranchLayoutException { List<String> linesWithoutBlank = lines.reject(String::isBlank); if (linesWithoutBlank.nonEmpty() && linesWithoutBlank.head().getIndentWidth(indentSpec.getIndentCharacter()) > 0) { int firstNonEmptyLineIndex = lines.indexOf(linesWithoutBlank.head()); assert firstNonEmptyLineIndex >= 0 : "Non-empty line not found"; throw new BranchLayoutException(firstNonEmptyLineIndex + 1, "The initial line of branch layout file must not be indented"); } Array<Tuple2<Integer, Integer>> lineIndexToIndentLevelAndParentLineIndex = Array.fill(linesWithoutBlank.size(), new Tuple2<>(-1, -1)); Array<Integer> levelToPresentParent = Array.fill(linesWithoutBlank.size(), -1); int previousLevel = 0; int lineIndex = 0; for (int realLineNumber = 0; realLineNumber < lines.length(); ++realLineNumber) { String line = lines.get(realLineNumber); if (line.isBlank()) { // Can't use lambda because `realLineNumber` is not effectively final LOG.debug("Line no ${realLineNumber + 1} is blank. Skipping"); continue; } if (!line.hasProperIndentationCharacter(indentSpec.getIndentCharacter())) { LOG.error("Line no ${realLineNumber + 1} has unexpected indentation character inconsistent with previous one"); throw new BranchLayoutException(realLineNumber + 1, "Line no ${realLineNumber + 1} in branch layout file has unexpected indentation " + "character inconsistent with previous one"); } int lineIndentWidth = line.getIndentWidth(indentSpec.getIndentCharacter()); int level = getIndentLevel(indentSpec, line, lineIndentWidth, realLineNumber); if (level - previousLevel > 1) { throw new BranchLayoutException(realLineNumber + 1, "One of branches in branch layout file has incorrect level in relation to its parent branch"); } @SuppressWarnings("index:argument") Integer parentLineIndex = level <= 0 ? -1 : levelToPresentParent.get(level - 1); Tuple2<Integer, Integer> levelAndParentLineIndex = new Tuple2<>(level, parentLineIndex); lineIndexToIndentLevelAndParentLineIndex = lineIndexToIndentLevelAndParentLineIndex.update(lineIndex, levelAndParentLineIndex); levelToPresentParent = levelToPresentParent.update(level, lineIndex); previousLevel = level; lineIndex++; } return lineIndexToIndentLevelAndParentLineIndex; } private @NonNegative int getIndentLevel(IndentSpec indentSpec, String line, @NonNegative int indent, @NonNegative int lineNumber) throws BranchLayoutException { if (indent == 0) { return 0; } if (indent % indentSpec.getIndentWidth() != 0) { throw new BranchLayoutException(lineNumber + 1, "Levels of indentation are not matching in branch layout file: " + "line `${line}` has ${indent} indent characters, but expected a multiply of ${indentSpec.getIndentWidth()}"); } return indent / indentSpec.getIndentWidth(); } }
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/branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutWriter.java
branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutWriter.java
package com.virtuslab.branchlayout.impl.readwrite; import java.io.IOException; import java.io.OutputStream; import io.vavr.collection.List; import lombok.CustomLog; import lombok.val; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutEntry; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.branchlayout.api.readwrite.IndentSpec; import com.virtuslab.qual.guieffect.IgnoreUIThreadUnsafeCalls; @CustomLog public class BranchLayoutWriter implements IBranchLayoutWriter { @IgnoreUIThreadUnsafeCalls("java.io.OutputStream.write([B)") @Override public void write(OutputStream outputStream, BranchLayout branchLayout, IndentSpec indentSpec) throws IOException { val lines = entriesToStringList(branchLayout.getRootEntries(), indentSpec, /* level */ 0); LOG.debug(() -> "Writing branch layout with indent character ASCII " + "code = ${indentSpec.getIndentCharacter()} and indent width = ${indentSpec.getIndentWidth()}"); lines.forEach(LOG::debug); outputStream.write(lines.mkString(System.lineSeparator()).getBytes()); } private List<String> entriesToStringList( List<BranchLayoutEntry> entries, IndentSpec indentSpec, @NonNegative int level) { List<String> stringList = List.empty(); for (val entry : entries) { val sb = new StringBuilder(); val count = level * indentSpec.getIndentWidth(); sb.append(String.valueOf(indentSpec.getIndentCharacter()).repeat(count)); sb.append(entry.getName()); String customAnnotation = entry.getCustomAnnotation(); if (customAnnotation != null) { sb.append(" ").append(customAnnotation); } List<String> resultForChildren = entriesToStringList(entry.getChildren(), indentSpec, level + 1); stringList = stringList.append(sb.toString()).appendAll(resultForChildren); } return stringList; } public IndentSpec deriveIndentSpec(List<String> lines) { return BranchLayoutFileUtils.deriveIndentSpec(lines); } }
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/branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutFileUtils.java
branchLayout/impl/src/main/java/com/virtuslab/branchlayout/impl/readwrite/BranchLayoutFileUtils.java
package com.virtuslab.branchlayout.impl.readwrite; import static com.virtuslab.branchlayout.api.readwrite.IndentSpec.SPACE; import static com.virtuslab.branchlayout.api.readwrite.IndentSpec.TAB; import io.vavr.collection.List; import io.vavr.collection.Stream; import lombok.CustomLog; import lombok.val; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; import com.virtuslab.branchlayout.api.readwrite.IndentSpec; @CustomLog public final class BranchLayoutFileUtils { private BranchLayoutFileUtils() {} public static final @Positive int DEFAULT_INDENT_WIDTH = 2; public static final char DEFAULT_INDENT_CHARACTER = SPACE; private static final IndentSpec DEFAULT_SPEC = new IndentSpec(DEFAULT_INDENT_CHARACTER, DEFAULT_INDENT_WIDTH); public static @NonNegative int getIndentWidth(String line, char indentCharacter) { return Stream.ofAll(line.chars().boxed()).takeWhile(c -> c == indentCharacter).size(); } public static IndentSpec deriveIndentSpec(List<String> lines) { LOG.debug(() -> "${lines.length()} line(s) found"); val firstLineWithBlankPrefixOption = lines.reject(String::isBlank) .find(line -> line.startsWith(String.valueOf(SPACE)) || line.startsWith(String.valueOf(TAB))); char indentCharacter = BranchLayoutFileUtils.DEFAULT_SPEC.getIndentCharacter(); int indentWidth = BranchLayoutFileUtils.DEFAULT_SPEC.getIndentWidth(); // Redundant non-emptiness check to satisfy IndexChecker if (firstLineWithBlankPrefixOption.isDefined() && !firstLineWithBlankPrefixOption.get().isEmpty()) { indentCharacter = firstLineWithBlankPrefixOption.get().charAt(0); indentWidth = getIndentWidth(firstLineWithBlankPrefixOption.get(), indentCharacter); // we are processing a line satisfying `line.startsWith(" ") || line.startsWith("\t")` assert indentWidth > 0 : "indent width is ${indentWidth} <= 0"; } IndentSpec indentSpec = new IndentSpec(indentCharacter, indentWidth); LOG.debug(() -> "Indent character is ${indentSpec.getIndentCharacter() == '\\t' ? \"TAB\" :" + " indentSpec.getIndentCharacter() == ' ' ? \"SPACE\" : \"'\" + indentSpec.getIndentCharacter() + \"'\"}"); LOG.debug(() -> "Indent width is ${indentSpec.getIndentWidth()}"); return indentSpec; } public static boolean hasProperIndentationCharacter(String line, char expectedIndentationCharacter) { char unexpectedIndentationCharacter = expectedIndentationCharacter == SPACE ? TAB : SPACE; return Stream.ofAll(line.toCharArray()) .takeWhile(c -> c != expectedIndentationCharacter) .headOption() .map(c -> c != unexpectedIndentationCharacter) .getOrElse(true); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/branchLayout/api/src/test/java/com/virtuslab/branchlayout/api/BranchLayoutTestSuite.java
branchLayout/api/src/test/java/com/virtuslab/branchlayout/api/BranchLayoutTestSuite.java
package com.virtuslab.branchlayout.api; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import io.vavr.collection.List; import lombok.val; import org.junit.jupiter.api.Test; public class BranchLayoutTestSuite { @Test public void shouldBeAbleToFindNextAndPreviousBranches() { // given String rootName = "root"; String parentName0 = "parent0"; String childName0 = "child0"; String childName1 = "child1"; String parentName1 = "parent1"; String childName2 = "child2"; /*- root root parent0 child0 child0 child1 child1 parent1 child2 */ List<BranchLayoutEntry> childBranches0 = List.of( new BranchLayoutEntry(childName0, /* customAnnotation */ null, List.empty()), new BranchLayoutEntry(childName1, /* customAnnotation */ null, List.empty())); val entry0 = new BranchLayoutEntry(parentName0, /* customAnnotation */ null, childBranches0); List<BranchLayoutEntry> childBranches1 = List.of( new BranchLayoutEntry(childName2, /* customAnnotation */ null, List.empty())); val entry1 = new BranchLayoutEntry(parentName1, /* customAnnotation */ null, childBranches1); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.of(entry0, entry1)); val branchLayout = new BranchLayout(List.of(rootEntry)); //then assertEquals(parentName1, branchLayout.findNextEntry(childName1).getName()); assertEquals(childName0, branchLayout.findPreviousEntry(childName1).getName()); assertEquals(childName0, branchLayout.findNextEntry(parentName0).getName()); assertEquals(parentName0, branchLayout.findPreviousEntry(childName0).getName()); assertEquals(childName1, branchLayout.findPreviousEntry(parentName1).getName()); assertNull(branchLayout.findPreviousEntry(rootName)); assertNull(branchLayout.findNextEntry(childName2)); } @Test public void givenSingleEntryLayout_nextAndPreviousShouldBeNull() { // given String rootName = "root"; val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.empty()); val branchLayout = new BranchLayout(List.of(rootEntry)); //then assertNull(branchLayout.findPreviousEntry(rootName)); assertNull(branchLayout.findNextEntry(rootName)); } @Test public void givenOnlyRootsEntryLayout_nextAndPreviousShouldBeCalculated() { // given String rootName = "root"; String rootName1 = "root1"; String rootName2 = "root2"; val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.empty()); val rootEntry1 = new BranchLayoutEntry(rootName1, /* customAnnotation */ null, List.empty()); val rootEntry2 = new BranchLayoutEntry(rootName2, /* customAnnotation */ null, List.empty()); val branchLayout = new BranchLayout(List.of(rootEntry, rootEntry1, rootEntry2)); //then assertNull(branchLayout.findPreviousEntry(rootName)); assertNull(branchLayout.findNextEntry(rootName2)); assertEquals(rootName2, branchLayout.findNextEntry(rootName1).getName()); assertEquals(rootName, branchLayout.findPreviousEntry(rootName1).getName()); assertEquals(rootName1, branchLayout.findPreviousEntry(rootName2).getName()); } @Test public void withBranchSlideOut_givenNonRootExistingBranch_slidesOut() { // given String rootName = "root"; String branchToSlideOutName = "parent"; String childName0 = "child0"; String childName1 = "child1"; /*- root root parent slide out child0 -----> child0 child1 child1 */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(childName0, /* customAnnotation */ null, List.empty()), new BranchLayoutEntry(childName1, /* customAnnotation */ null, List.empty())); val entry = new BranchLayoutEntry(branchToSlideOutName, /* customAnnotation */ null, childBranches); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.of(entry)); val branchLayout = new BranchLayout(List.of(rootEntry)); assertNull(rootEntry.getParent()); assertEquals(rootName, rootEntry.getChildren().get(0).getParent().getName()); assertEquals(branchToSlideOutName, rootEntry.getChildren().get(0).getChildren().get(0).getParent().getName()); assertEquals(branchToSlideOutName, rootEntry.getChildren().get(0).getChildren().get(1).getParent().getName()); // when BranchLayout result = branchLayout.slideOut(branchToSlideOutName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(2, children.size()); assertEquals(childName0, children.get(0).getName()); assertEquals(childName1, children.get(1).getName()); assertNull(rootEntry.getParent()); assertEquals(rootName, children.get(0).getParent().getName()); assertEquals(rootName, children.get(1).getParent().getName()); } @Test public void withBranchRename_givenBranchLayout_renamesChild() { // given String rootName = "root"; String branchToRename = "child"; String newBranchName = "kinder"; /*- root rename root child -----> kinder */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(branchToRename, /* customAnnotation */ null, List.empty())); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(rootEntry)); // when BranchLayout result = branchLayout.rename(branchToRename, newBranchName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(1, children.size()); assertEquals(newBranchName, children.get(0).getName()); } @Test public void withBranchRename_givenBranchLayout_renamesRoot() { // given String rootName = "root"; String rootAnnotation = "this is root"; String child = "child"; String newRootName = "master"; /*- root rename master child -----> child */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(child, /* customAnnotation */ null, List.empty())); val rootEntry = new BranchLayoutEntry(rootName, rootAnnotation, childBranches); val branchLayout = new BranchLayout(List.of(rootEntry)); // when BranchLayout result = branchLayout.rename(rootName, newRootName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(newRootName, result.getRootEntries().get(0).getName()); assertEquals(rootAnnotation, result.getRootEntries().get(0).getCustomAnnotation()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(1, children.size()); } @Test public void withBranchRename_givenBranchLayout_renamesToTheSameName() { // given String rootName = "root"; String child = "child"; /*- root rename root child -----> child */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(child, /* customAnnotation */ null, List.empty())); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(rootEntry)); // when BranchLayout result = branchLayout.rename(rootName, rootName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(1, children.size()); } @Test public void withBranchRename_givenBranchLayout_renameOfNonexistentDoesNothing() { // given String rootName = "root"; String child = "child"; String nonExisting = "fix/foo"; String newNonExistingName = "bugfix/bar"; /*- root rename root child -----> child */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(child, /* customAnnotation */ null, List.empty())); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(rootEntry)); // when BranchLayout result = branchLayout.rename(nonExisting, newNonExistingName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(1, children.size()); } @Test public void withBranchSlideOut_givenDuplicatedBranch_slidesOut() { // given String rootName = "root"; String branchToSlideOutName = "child"; /*- root root child slide out child -----> */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(branchToSlideOutName, /* customAnnotation */ null, List.empty()), new BranchLayoutEntry(branchToSlideOutName, /* customAnnotation */ null, List.empty())); val rootEntry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(rootEntry)); // when BranchLayout result = branchLayout.slideOut(branchToSlideOutName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); val children = result.getRootEntries().get(0).getChildren(); assertEquals(0, children.size()); } @Test public void withBranchSlideOut_givenRootBranchWithChildren_slidesOut() { // given String rootName = "root"; String childName0 = "child0"; String childName1 = "child1"; /*- root slide out child0 -----> child0 child1 child1 */ List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(childName0, /* customAnnotation */ null, List.empty()), new BranchLayoutEntry(childName1, /* customAnnotation */ null, List.empty())); val entry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(entry)); // when BranchLayout result = branchLayout.slideOut(rootName); // then assertEquals(2, result.getRootEntries().size()); assertEquals(childName0, result.getRootEntries().get(0).getName()); assertEquals(childName1, result.getRootEntries().get(1).getName()); } @Test public void withBranchSlideOut_givenDuplicatedBranchUnderItself_slidesOut() { // given String rootName = "root"; String childName = "child"; /*- root slide out root child -----> child */ val childBranchEntry = new BranchLayoutEntry(childName, /* customAnnotation */ null, List.empty()); List<BranchLayoutEntry> childBranches = List.of( new BranchLayoutEntry(childName, /* customAnnotation */ null, List.of(childBranchEntry))); val entry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, childBranches); val branchLayout = new BranchLayout(List.of(entry)); // when BranchLayout result = branchLayout.slideOut(childName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(rootName, result.getRootEntries().get(0).getName()); assertEquals(0, result.getRootEntries().get(0).getChildren().size()); } @Test public void withBranchSlideOut_givenSingleRootBranch_slidesOut() { // given val rootName = "root"; /*- root slide out -----> */ val entry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.empty()); val branchLayout = new BranchLayout(List.of(entry)); // when BranchLayout result = branchLayout.slideOut(rootName); // then assertEquals(0, result.getRootEntries().size()); } @Test public void withBranchSlideOut_givenTwoRootBranches_slidesOut() { // given val rootName = "root"; val masterRootName = "master"; /*- root slide out master master -----> */ val entry = new BranchLayoutEntry(rootName, /* customAnnotation */ null, List.empty()); val masterEntry = new BranchLayoutEntry(masterRootName, /* customAnnotation */ null, List.empty()); val branchLayout = new BranchLayout(List.of(entry, masterEntry)); // when BranchLayout result = branchLayout.slideOut(rootName); // then assertEquals(1, result.getRootEntries().size()); assertEquals(masterRootName, result.getRootEntries().get(0).getName()); } @Test public void withBranchSlideOut_givenNonExistingBranch_noExceptionThrown() { // given val branchToSlideOutName = "branch"; val branchLayout = new BranchLayout(List.empty()); // when BranchLayout result = branchLayout.slideOut(branchToSlideOutName); // then no exception thrown assertTrue(result.getRootEntries().isEmpty()); } private static BranchLayout getExampleBranchLayout() { return new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))))); } @Test public void withBranchLayouts_givenTheyAreEquivalent_shouldBeConsideredEqual() { assertEquals(getExampleBranchLayout(), getExampleBranchLayout()); } @Test public void withBranchLayouts_givenOneIsEmpty_shouldBeConsideredNotEqual() { val emptyBranchLayout = new BranchLayout(List.empty()); val branchLayout = getExampleBranchLayout(); assertNotEquals(branchLayout, emptyBranchLayout); assertNotEquals(emptyBranchLayout, branchLayout); } @Test public void withBranchLayouts_givenOneHasExtraChildBranch_shouldBeConsideredNotEqual() { val branchLayout = getExampleBranchLayout(); val branchLayoutWithExtraChildBranch = new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.of(new BranchLayoutEntry("EXTRA_BRANCH", /* customAnnotation */ null, List.empty()))), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))))); assertNotEquals(branchLayout, branchLayoutWithExtraChildBranch); assertNotEquals(branchLayoutWithExtraChildBranch, branchLayout); } @Test public void withBranchLayouts_givenOneHasExtraRootBranch_shouldBeConsideredNotEqual() { val branchLayout = getExampleBranchLayout(); val branchLayoutWithExtraRootBranch = new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))), new BranchLayoutEntry("EXTRA_BRANCH", /* customAnnotation */ null, List.empty()))); assertNotEquals(branchLayout, branchLayoutWithExtraRootBranch); assertNotEquals(branchLayoutWithExtraRootBranch, branchLayout); } @Test public void withBranchLayouts_givenOneHasDifferentRootBranchName_shouldBeConsideredNotEqual() { val branchLayout = getExampleBranchLayout(); val branchLayoutDifferentRootName = new BranchLayout(List.of( new BranchLayoutEntry("DIFFERENT_NAME", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))))); assertNotEquals(branchLayout, branchLayoutDifferentRootName); assertNotEquals(branchLayoutDifferentRootName, branchLayout); } @Test public void withBranchLayouts_givenOneHasDifferentChildBranchName_shouldBeConsideredNotEqual() { val branchLayout = getExampleBranchLayout(); val branchLayoutDifferentLeafName = new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("DIFFERENT_NAME", /* customAnnotation */ null, List.empty()))))); assertNotEquals(branchLayout, branchLayoutDifferentLeafName); assertNotEquals(branchLayoutDifferentLeafName, branchLayout); } @Test public void withBranchLayouts_givenOneHasDifferentChildBranchCustomAnnotation_shouldBeConsideredNotEqual() { val branchLayout = getExampleBranchLayout(); val branchLayoutDifferentAnnotation = new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("B", "DIFFERENT_ANNOTATION", List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))))); assertNotEquals(branchLayout, branchLayoutDifferentAnnotation); assertNotEquals(branchLayoutDifferentAnnotation, branchLayout); } @Test public void withBranchLayouts_givenTheyAreEquivalentButShuffled_shouldBeConsideredEqual() { val branchLayout = new BranchLayout(List.of( new BranchLayoutEntry("A", /* customAnnotation */ null, List.of(new BranchLayoutEntry("AB", "ANNOTATION", List.empty()), new BranchLayoutEntry("AA", /* customAnnotation */ null, List.empty()))), new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))))); val branchLayoutShuffled = new BranchLayout(List.of( new BranchLayoutEntry("B", /* customAnnotation */ null, List.of(new BranchLayoutEntry("BA", /* customAnnotation */ null, List.empty()))), new BranchLayoutEntry("A", /* customAnnotation */ null, List.of(new BranchLayoutEntry("AA", /* customAnnotation */ null, List.empty()), new BranchLayoutEntry("AB", "ANNOTATION", List.empty()))))); assertEquals(branchLayout, branchLayoutShuffled); assertEquals(branchLayoutShuffled, branchLayout); } }
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/EntryDoesNotExistException.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/EntryDoesNotExistException.java
package com.virtuslab.branchlayout.api; import lombok.experimental.StandardException; @StandardException @SuppressWarnings("nullness:argument") public class EntryDoesNotExistException extends BranchLayoutException {}
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayoutEntry.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayoutEntry.java
package com.virtuslab.branchlayout.api; import java.util.Comparator; import java.util.Objects; import io.vavr.collection.List; import lombok.AccessLevel; import lombok.Getter; import lombok.ToString; import lombok.With; import lombok.val; import org.checkerframework.checker.nullness.qual.Nullable; /** * Class that encapsulates a single branch and a list of its children. <br> * Two {@code BranchLayoutEntry} objects are equal when their names, their custom annotations * and their children are <b>all</b> equal (recursively checked for children). * Parents are <b>not</b> taken into account in equality checks to avoid infinite recursion. */ @SuppressWarnings("interning:not.interned") // to allow for `==` comparison in Lombok-generated `with...` methods @ToString public final class BranchLayoutEntry { @Getter @With private final String name; @Getter @With private final @Nullable String customAnnotation; @Getter @With(AccessLevel.PRIVATE) private final @Nullable BranchLayoutEntry parent; @Getter @With private final List<BranchLayoutEntry> children; // Extracted a separate, all-args constructor solely for the sake of Lombok to implement `withChildren` @SuppressWarnings("nullness:argument") // to allow for passing not fully initialized `this` to `withParent` private BranchLayoutEntry(String name, @Nullable String customAnnotation, @Nullable BranchLayoutEntry parent, List<BranchLayoutEntry> children) { this.name = name; this.customAnnotation = customAnnotation; this.parent = parent; this.children = children.map(child -> child.withParent(this)); } public BranchLayoutEntry(String name, @Nullable String customAnnotation, List<BranchLayoutEntry> children) { this(name, customAnnotation, /* parent */ null, children); } @ToString.Include(name = "children") // avoid recursive `toString` calls on children private List<String> getChildNames() { return children.map(e -> e.name); } @ToString.Include(name = "parent") // avoid recursive `toString` calls on parent private @Nullable String getParentName() { return parent != null ? parent.name : null; } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } else if (!(other instanceof BranchLayoutEntry)) { return false; } else { val otherEntry = (BranchLayoutEntry) other; val areNamesSame = this.name.equals(otherEntry.name); val areCustomAnnotationsSame = Objects.equals(this.customAnnotation, otherEntry.customAnnotation); if (areNamesSame && areCustomAnnotationsSame && this.children.size() == otherEntry.children.size()) { val entryNameComparator = Comparator.comparing(BranchLayoutEntry::getName); val sortedSelfEntries = this.children.sorted(entryNameComparator); val sortedOtherEntries = otherEntry.children.sorted(entryNameComparator); return sortedSelfEntries.zip(sortedOtherEntries) .forAll(entryTuple -> entryTuple._1.equals(entryTuple._2)); } return false; } } @Override public int hashCode() { return Objects.hash(name, customAnnotation, children); } }
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayout.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayout.java
package com.virtuslab.branchlayout.api; import java.util.Comparator; import java.util.Objects; import io.vavr.Tuple; import io.vavr.collection.List; import io.vavr.collection.Map; import lombok.Getter; import lombok.val; import org.checkerframework.checker.index.qual.LTLengthOf; import org.checkerframework.checker.nullness.qual.Nullable; /** * Two {@code BranchLayout} objects are equal when their root entries (after sorting by name) are equal. * * @see BranchLayoutEntry */ public class BranchLayout { @Getter private final List<BranchLayoutEntry> rootEntries; private final List<BranchLayoutEntry> allEntries; private final Map<String, BranchLayoutEntry> entryByName; public BranchLayout(List<BranchLayoutEntry> rootEntries) { this.rootEntries = rootEntries; this.allEntries = rootEntries.flatMap(BranchLayout::collectEntriesRecursively); this.entryByName = allEntries.toMap(entry -> Tuple.of(entry.getName(), entry)); } private static List<BranchLayoutEntry> collectEntriesRecursively(BranchLayoutEntry entry) { return entry.getChildren().flatMap(BranchLayout::collectEntriesRecursively).prepend(entry); } public @Nullable BranchLayoutEntry getEntryByName(String branchName) { return entryByName.get(branchName).getOrNull(); } public boolean hasEntry(String branchName) { return getEntryByName(branchName) != null; } public boolean isEntryDuplicated(String branchName) { val numberOfEntriesForBranchName = allEntries .count(entry -> entry.getName().equals(branchName)); return numberOfEntriesForBranchName > 1; } public @Nullable BranchLayoutEntry findNextEntry(String branchName) { val entriesOrderedList = allEntries.map(BranchLayoutEntry::getName); val currentIndex = entriesOrderedList.indexOf(branchName); if (currentIndex > -1 && currentIndex + 1 < entriesOrderedList.length()) { @LTLengthOf("entriesOrderedList") int nextIndex = currentIndex + 1; return getEntryByName(entriesOrderedList.get(nextIndex)); } return null; } public @Nullable String findNextEntryName(String branchName) { val nextEntry = findNextEntry(branchName); return nextEntry != null ? nextEntry.getName() : null; } public @Nullable BranchLayoutEntry findPreviousEntry(String branchName) { val entriesOrderedList = allEntries.map(BranchLayoutEntry::getName); val currentIndex = entriesOrderedList.indexOf(branchName); if (currentIndex > 0 && currentIndex < entriesOrderedList.length()) { @LTLengthOf("entriesOrderedList") int previousIndex = currentIndex - 1; return getEntryByName(entriesOrderedList.get(previousIndex)); } return null; } public BranchLayout rename(String currentBranchName, String newBranchName) { if (currentBranchName.equals(newBranchName)) { return new BranchLayout(rootEntries); } return new BranchLayout(rootEntries.flatMap(rootEntry -> rename(rootEntry, currentBranchName, newBranchName))); } private List<BranchLayoutEntry> rename(BranchLayoutEntry entry, String currentBranchName, String newBranchName) { val newChildren = entry.getChildren().flatMap(child -> rename(child, currentBranchName, newBranchName)); if (entry.getName().equals(currentBranchName)) { return List.of(entry.withName(newBranchName)); } else { return List.of(entry.withChildren(newChildren)); } } public BranchLayout slideOut(String branchName) { return new BranchLayout(rootEntries.flatMap(rootEntry -> slideOut(rootEntry, branchName))); } private List<BranchLayoutEntry> slideOut(BranchLayoutEntry entry, String entryNameToSlideOut) { val newChildren = entry.getChildren().flatMap(child -> slideOut(child, entryNameToSlideOut)); if (entry.getName().equals(entryNameToSlideOut)) { return newChildren; } else { return List.of(entry.withChildren(newChildren)); } } public BranchLayout slideIn(String parentBranchName, BranchLayoutEntry entryToSlideIn) throws EntryDoesNotExistException, EntryIsDescendantOfException { val parentEntry = getEntryByName(parentBranchName); if (parentEntry == null) { throw new EntryDoesNotExistException("Parent branch entry '${parentBranchName}' does not exist"); } val entry = getEntryByName(entryToSlideIn.getName()); val entryAlreadyExists = entry != null; if (entry != null && isDescendant(/* presumedAncestor */ entry, /* presumedDescendant */ parentEntry)) { throw new EntryIsDescendantOfException( "Entry '${parentEntry.getName()}' is a descendant of entry '${entryToSlideIn.getName()}'"); } val newRootEntries = entryAlreadyExists ? removeEntry(/* branchLayout */ this, entryToSlideIn.getName()) : rootEntries; return new BranchLayout(newRootEntries.map(rootEntry -> slideIn(rootEntry, entryToSlideIn, parentEntry))); } private static boolean isDescendant(BranchLayoutEntry presumedAncestor, BranchLayoutEntry presumedDescendant) { if (presumedAncestor.getChildren().contains(presumedDescendant)) { return true; } return presumedAncestor.getChildren().exists(e -> isDescendant(e, presumedDescendant)); } private static List<BranchLayoutEntry> removeEntry(BranchLayout branchLayout, String branchName) { val rootEntries = branchLayout.getRootEntries(); if (rootEntries.map(e -> e.getName()).exists(name -> name.equals(branchName))) { return rootEntries.reject(e -> e.getName().equals(branchName)); } else { return removeEntry(rootEntries, branchName); } } private static List<BranchLayoutEntry> removeEntry(List<BranchLayoutEntry> entries, String branchName) { return entries.reject(e -> e.getName().equals(branchName)) .map(e -> e.withChildren(removeEntry(e.getChildren(), branchName))); } private static BranchLayoutEntry slideIn( BranchLayoutEntry entry, BranchLayoutEntry entryToSlideIn, BranchLayoutEntry parent) { val children = entry.getChildren(); if (entry.getName().equals(parent.getName())) { return entry.withChildren(children.append(entryToSlideIn)); } else { return entry.withChildren(children.map(child -> slideIn(child, entryToSlideIn, parent))); } } @Override public final boolean equals(@Nullable Object other) { if (this == other) { return true; } else if (!(other instanceof BranchLayout)) { return false; } else { val otherLayout = (BranchLayout) other; if (this.rootEntries.size() == otherLayout.rootEntries.size()) { val entryNameComparator = Comparator.comparing(BranchLayoutEntry::getName); val sortedSelfRootEntries = this.rootEntries.sorted(entryNameComparator); val sortedOtherRootEntries = otherLayout.rootEntries.sorted(entryNameComparator); return sortedSelfRootEntries.zip(sortedOtherRootEntries) .forAll(rootEntryTuple -> rootEntryTuple._1.equals(rootEntryTuple._2)); } return false; } } @Override public final int hashCode() { return Objects.hash(rootEntries); } }
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayoutException.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/BranchLayoutException.java
package com.virtuslab.branchlayout.api; import lombok.Getter; import org.checkerframework.checker.index.qual.Positive; import org.checkerframework.checker.nullness.qual.Nullable; public class BranchLayoutException extends Exception { @Getter private final @Nullable @Positive Integer errorLine; public BranchLayoutException(@Nullable @Positive Integer errorLine, String message) { super(message + (errorLine != null ? ". Problematic line number: " + errorLine : "")); this.errorLine = errorLine; } public BranchLayoutException(String message) { this(null, message); } public BranchLayoutException(@Nullable @Positive Integer errorLine, String message, Throwable e) { super(message, e); this.errorLine = errorLine; } public BranchLayoutException(String message, Throwable e) { this(null, message, 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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/EntryIsDescendantOfException.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/EntryIsDescendantOfException.java
package com.virtuslab.branchlayout.api; import lombok.experimental.StandardException; @StandardException @SuppressWarnings("nullness:argument") public class EntryIsDescendantOfException extends BranchLayoutException {}
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IBranchLayoutReader.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IBranchLayoutReader.java
package com.virtuslab.branchlayout.api.readwrite; import java.io.InputStream; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutException; public interface IBranchLayoutReader { BranchLayout read(InputStream inputStream) throws BranchLayoutException; }
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IndentSpec.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IndentSpec.java
package com.virtuslab.branchlayout.api.readwrite; import lombok.Data; import org.checkerframework.checker.index.qual.Positive; @Data public class IndentSpec { public static final char TAB = '\t'; public static final char SPACE = ' '; private final char indentCharacter; private final @Positive int indentWidth; }
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/branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IBranchLayoutWriter.java
branchLayout/api/src/main/java/com/virtuslab/branchlayout/api/readwrite/IBranchLayoutWriter.java
package com.virtuslab.branchlayout.api.readwrite; import java.io.IOException; import java.io.OutputStream; import io.vavr.collection.List; import com.virtuslab.branchlayout.api.BranchLayout; public interface IBranchLayoutWriter { void write(OutputStream outputStream, BranchLayout branchLayout, IndentSpec indentSpec) throws IOException; IndentSpec deriveIndentSpec(List<String> lines); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileType.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileType.java
package com.virtuslab.gitmachete.frontend.file; import javax.swing.Icon; import com.intellij.openapi.fileTypes.LanguageFileType; import com.virtuslab.gitmachete.frontend.defs.FileTypeIds; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteLanguage; import com.virtuslab.gitmachete.frontend.icons.MacheteIcons; public final class MacheteFileType extends LanguageFileType { public static final MacheteFileType instance = new MacheteFileType(); private MacheteFileType() { super(MacheteLanguage.instance); } @Override public boolean isReadOnly() { return false; } @Override public String getName() { return FileTypeIds.NAME; } @Override public String getDescription() { return "Branch layout file for Git Machete"; } @Override public String getDefaultExtension() { return "machete"; } @Override public Icon getIcon() { return MacheteIcons.MACHETE_FILE; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileWriter.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileWriter.java
package com.virtuslab.gitmachete.frontend.file; import java.io.BufferedOutputStream; import java.io.IOException; import java.nio.file.Path; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFileManager; import io.vavr.collection.List; import lombok.CustomLog; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.qual.guieffect.IgnoreUIThreadUnsafeCalls; @CustomLog public final class MacheteFileWriter { private MacheteFileWriter() {} /** * The method for writing the branch layout using IntelliJ's VFS API, should be executed on the UI thread and wrapped in a WriteAction. * @param path a path to file where branch layout should be written * @param branchLayout a layout to be written * @param backupOldFile a flag stating if the old layout file should be backed-up * @param requestor an object requesting the write execution (can be used for debugging when listening for the file changes) */ @IgnoreUIThreadUnsafeCalls("java.io.BufferedOutputStream.close()") @UIEffect public static void writeBranchLayout( Path path, IBranchLayoutWriter branchLayoutWriter, BranchLayout branchLayout, boolean backupOldFile, Object requestor) throws IOException { LOG.debug(() -> "Writing branch layout to (${path}), branchLayout = ${branchLayout}, backupOldFile = ${backupOldFile}"); val parentPath = path.getParent(); assert parentPath != null : "Can't get parent directory of branch layout file"; val parentDirVFile = VirtualFileManager.getInstance().findFileByNioPath(parentPath); assert parentDirVFile != null : "Can't get parent directory of branch layout file"; val macheteFileName = path.getFileName(); assert macheteFileName != null : "Invalid path to machete file"; var macheteVFile = parentDirVFile.findChild(macheteFileName.toString()); if (macheteVFile != null) { if (backupOldFile) { val backupFileName = macheteVFile.getName() + "~"; val backupVFile = parentDirVFile.findChild(backupFileName); if (backupVFile != null) { backupVFile.delete(requestor); } VfsUtilCore.copyFile(requestor, macheteVFile, parentDirVFile, backupFileName); } } else { macheteVFile = parentDirVFile.createChildData(requestor, macheteFileName.toString()); } try (val outputStream = new BufferedOutputStream(macheteVFile.getOutputStream(requestor))) { val fileLines = List.ofAll(VfsUtilCore.loadText(macheteVFile).lines()); val indentSpec = branchLayoutWriter.deriveIndentSpec(fileLines); branchLayoutWriter.write(outputStream, branchLayout, indentSpec); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileReader.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileReader.java
package com.virtuslab.gitmachete.frontend.file; import java.io.IOException; import java.nio.file.Path; import com.intellij.openapi.vfs.VirtualFileManager; import io.vavr.collection.List; import lombok.CustomLog; import lombok.val; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutException; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader; import com.virtuslab.qual.guieffect.IgnoreUIThreadUnsafeCalls; @CustomLog public final class MacheteFileReader { private MacheteFileReader() {} /** * Method for reading branch layout using IntelliJ's VFS API, should be used inside a ReadAction */ @IgnoreUIThreadUnsafeCalls("java.io.InputStream.close()") public static BranchLayout readBranchLayout(Path path, IBranchLayoutReader branchLayoutReader) throws BranchLayoutException { LOG.debug(() -> "Reading branch layout from (${path}), branchLayoutReader = ${branchLayoutReader}"); val macheteVFile = VirtualFileManager.getInstance().findFileByNioPath(path); BranchLayout resultBranchLayout = new BranchLayout(List.empty()); if (macheteVFile != null) { try (val inputStream = macheteVFile.getInputStream()) { resultBranchLayout = branchLayoutReader.read(inputStream); } catch (IOException e) { throw new BranchLayoutException("Error while reading (${path})", e); } } return resultBranchLayout; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteCompletionContributor.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteCompletionContributor.java
package com.virtuslab.gitmachete.frontend.file; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.PlainPrefixMatcher; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.psi.PsiFile; import com.intellij.ui.TextFieldWithAutoCompletionListProvider; import lombok.experimental.ExtensionMethod; import lombok.val; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod({MacheteFileUtils.class}) public class MacheteCompletionContributor extends CompletionContributor implements DumbAware { @Override @UIThreadUnsafe public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) { PsiFile file = parameters.getOriginalFile(); val branchNames = file.getBranchNamesForPsiMacheteFile(); if (branchNames.isEmpty()) { return; } /* * {@link CompletionResultSet#stopHere} marks the result set as stopped. Completion service calls contributors as long as * everyone gets called or result set get marked as stopped. The following call allows to avoid other contributor * invocations (performance). * * See {@link com.intellij.codeInsight.completion.CompletionService#getVariantsFromContributors} */ result.stopHere(); String prefix = getCompletionPrefix(parameters); val matcher = new PlainPrefixMatcher(prefix, /* prefixMatchesOnly */ true); val completionResultSet = result.caseInsensitive().withPrefixMatcher(matcher); for (String branchName : branchNames) { ProgressManager.checkCanceled(); completionResultSet.addElement(LookupElementBuilder.create(branchName)); } } public static String getCompletionPrefix(CompletionParameters parameters) { String text = parameters.getOriginalFile().getText(); int offset = parameters.getOffset(); return getCompletionPrefix(text, offset); } /** * Sadly the original method {@link TextFieldWithAutoCompletionListProvider#getCompletionPrefix} * cannot be used as it does not take '\t' into account. */ private static String getCompletionPrefix(String text, int offset) { int lastSpaceIdx = text.lastIndexOf(' ', offset - 1) + 1; int lastTabIdx = text.lastIndexOf('\t', offset - 1) + 1; int lastNewLine = text.lastIndexOf(System.lineSeparator(), offset - 1) + 1; val max = Math.max(Math.max(lastSpaceIdx, lastTabIdx), lastNewLine); assert max <= offset : "File offset less than max indent/new line character index"; assert offset <= text.length() : "File text length less than offset"; return text.substring(max, offset); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/ReparseMacheteFileOnGitRepositoryChange.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/ReparseMacheteFileOnGitRepositoryChange.java
package com.virtuslab.gitmachete.frontend.file; import static com.intellij.openapi.application.ModalityState.NON_MODAL; import static com.virtuslab.gitmachete.frontend.file.MacheteFileUtils.getMacheteVirtualFileIfSelected; import com.intellij.openapi.project.Project; import com.intellij.util.FileContentUtilCore; import com.intellij.util.ModalityUiUtil; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryChangeListener; import lombok.RequiredArgsConstructor; import lombok.val; @RequiredArgsConstructor public class ReparseMacheteFileOnGitRepositoryChange implements GitRepositoryChangeListener { private final Project project; @Override public void repositoryChanged(GitRepository repository) { // Note that if machete file is just opened but NOT selected, // then it's apparently always getting reparsed once selected. // The only problematic case is when machete file is already selected, and the underlying git repository changes. // Unless a reparsing is forced, red squiggles marking a non-existent branch will stick around // even once that branch has already been created, e.g. by user firing our Alt+Enter quick fix. val macheteVirtualFile = getMacheteVirtualFileIfSelected(project); if (macheteVirtualFile != null) { ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> FileContentUtilCore.reparseFiles(macheteVirtualFile)); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileUtils.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileUtils.java
package com.virtuslab.gitmachete.frontend.file; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import io.vavr.collection.List; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod(GitVfsUtils.class) public final class MacheteFileUtils { private MacheteFileUtils() {} public static String getSampleMacheteFileContents() { return """ develop allow-ownership-link PR #123 build-chain call-ws PR #124 master hotfix/add-trigger PR #127 """; } @UIThreadUnsafe public static List<String> getBranchNamesForPsiMacheteFile(PsiFile psiFile) { val gitRepository = findGitRepositoryForPsiMacheteFile(psiFile); if (gitRepository == null) { return List.empty(); } return List.ofAll(gitRepository.getInfo().getLocalBranchesWithHashes().keySet()) .map(localBranch -> localBranch.getName()); } @UIThreadUnsafe public static @Nullable GitRepository findGitRepositoryForPsiMacheteFile(PsiFile psiFile) { val project = psiFile.getProject(); return List.ofAll(GitRepositoryManager.getInstance(project).getRepositories()) .find(repository -> { val macheteFile = repository.getMacheteFile(); return macheteFile != null && macheteFile.equals(psiFile.getVirtualFile()); }).getOrNull(); } @UIEffect public static void saveDocument(PsiFile file) { val fileDocManager = FileDocumentManager.getInstance(); val document = fileDocManager.getDocument(file.getVirtualFile()); if (document != null) { fileDocManager.saveDocument(document); } } public static @Nullable VirtualFile getMacheteVirtualFileIfSelected(Project project) { val fileEditorManager = FileEditorManager.getInstance(project); return List.of(fileEditorManager.getSelectedFiles()) .find(virtualFile -> virtualFile.getFileType().equals(MacheteFileType.instance)).getOrNull(); } /** * "Selected" = open AND focused. * Note that there can be multiple selected files in the given project, e.g. in case of split editors. */ public static boolean isMacheteFileSelected(Project project) { return getMacheteVirtualFileIfSelected(project) != null; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileViewProviderFactory.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/MacheteFileViewProviderFactory.java
package com.virtuslab.gitmachete.frontend.file; import com.intellij.lang.Language; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.FileViewProvider; import com.intellij.psi.FileViewProviderFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.SingleRootFileViewProvider; public class MacheteFileViewProviderFactory implements FileViewProviderFactory { @Override public FileViewProvider createFileViewProvider(VirtualFile file, Language language, PsiManager manager, boolean eventSystemEnabled) { return new SingleRootFileViewProvider(manager, file, eventSystemEnabled, language) { @Override protected boolean shouldCreatePsi() { return true; } }; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/quickfix/CreateBranchQuickFix.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/quickfix/CreateBranchQuickFix.java
package com.virtuslab.gitmachete.frontend.file.quickfix; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import java.util.Collections; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.util.IntentionFamilyName; import com.intellij.codeInspection.util.IntentionName; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import git4idea.branch.GitBrancher; import git4idea.repo.GitRepository; import lombok.RequiredArgsConstructor; import lombok.experimental.ExtensionMethod; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.qual.async.ContinuesInBackground; @RequiredArgsConstructor @ExtensionMethod({GitMacheteBundle.class}) public class CreateBranchQuickFix implements IntentionAction { private final String branch; private final String parentBranch; private final PsiFile macheteFile; private final @Nullable GitRepository gitRepository; @Override public @IntentionName String getText() { return getNonHtmlString("action.GitMachete.MacheteAnnotator.IntentionAction.create-nonexistent-branch").fmt(branch, parentBranch); } @Override public @IntentionFamilyName String getFamilyName() { return "Git Machete"; } @Override public boolean isAvailable(Project project, Editor editor, PsiFile file) { return true; } @Override @ContinuesInBackground public void invoke(Project project, Editor editor, PsiFile file) { createNewBranchFromParent(project); } @Override public boolean startInWriteAction() { return false; } @ContinuesInBackground private void createNewBranchFromParent(Project project) { if (gitRepository != null) { GitBrancher.getInstance(project).createBranch(branch, Collections.singletonMap(gitRepository, parentBranch)); } else { throw new RuntimeException("Unable to create new branch due to: git repository not found for " + macheteFile.getVirtualFile().getPath() + " file."); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteLexerAdapter.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteLexerAdapter.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.lexer.FlexAdapter; public class MacheteLexerAdapter extends FlexAdapter { @SuppressWarnings("nullness:argument") public MacheteLexerAdapter() { super(new MacheteGeneratedLexer(/* in */ null)); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteTokenType.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteTokenType.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.psi.tree.IElementType; import lombok.ToString; import org.jetbrains.annotations.NonNls; @ToString public class MacheteTokenType extends IElementType { public MacheteTokenType(@NonNls String debugName) { super(debugName, MacheteLanguage.instance); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteParserDefinition.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteParserDefinition.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.lang.ASTNode; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; public class MacheteParserDefinition implements ParserDefinition { public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); public static final TokenSet COMMENTS = TokenSet.create(MacheteGeneratedElementTypes.COMMENT); public static final IFileElementType FILE = new IFileElementType(MacheteLanguage.instance); @Override public Lexer createLexer(Project project) { return new MacheteLexerAdapter(); } @Override public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } // Even if we don't support comments, this element is part of the ParserDefinition interface. // So - we need to provide something here. @Override public TokenSet getCommentTokens() { return COMMENTS; } @Override public TokenSet getStringLiteralElements() { return TokenSet.EMPTY; } @Override public PsiParser createParser(final Project project) { return new MacheteGeneratedParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } @Override public PsiFile createFile(FileViewProvider viewProvider) { return new MacheteFile(viewProvider); } @Override public SpaceRequirements spaceExistenceTypeBetweenTokens(ASTNode left, ASTNode right) { return SpaceRequirements.MAY; } @Override public PsiElement createElement(ASTNode node) { return MacheteGeneratedElementTypes.Factory.createElement(node); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteFile.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteFile.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.virtuslab.gitmachete.frontend.defs.FileTypeIds; import com.virtuslab.gitmachete.frontend.file.MacheteFileType; public class MacheteFile extends PsiFileBase { public MacheteFile(FileViewProvider viewProvider) { super(viewProvider, MacheteLanguage.instance); } @Override public FileType getFileType() { return MacheteFileType.instance; } @Override public String toString() { return FileTypeIds.NAME; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteLanguage.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteLanguage.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.lang.Language; public final class MacheteLanguage extends Language { public static final MacheteLanguage instance = new MacheteLanguage(); private MacheteLanguage() { super("Git Machete"); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteElementType.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/grammar/MacheteElementType.java
package com.virtuslab.gitmachete.frontend.file.grammar; import com.intellij.psi.tree.IElementType; public class MacheteElementType extends IElementType { public MacheteElementType(String debugName) { super(debugName, MacheteLanguage.instance); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteSyntaxHighlighterFactory.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteSyntaxHighlighterFactory.java
package com.virtuslab.gitmachete.frontend.file.highlighting; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.checkerframework.checker.nullness.qual.Nullable; public class MacheteSyntaxHighlighterFactory extends SyntaxHighlighterFactory { @Override public SyntaxHighlighter getSyntaxHighlighter(@Nullable Project project, @Nullable VirtualFile virtualFile) { return new MacheteSyntaxHighlighter(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteAnnotator.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteAnnotator.java
package com.virtuslab.gitmachete.frontend.file.highlighting; import static com.intellij.openapi.application.ModalityState.NON_MODAL; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.nio.file.Path; import java.util.OptionalInt; import com.intellij.codeInsight.hint.HintManager; import com.intellij.diagnostic.PluginException; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.DumbAware; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ModalityUiUtil; import git4idea.repo.GitRepository; import lombok.Data; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutException; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader; import com.virtuslab.gitmachete.frontend.file.MacheteFileReader; import com.virtuslab.gitmachete.frontend.file.MacheteFileUtils; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteFile; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteGeneratedBranch; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteGeneratedElementTypes; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteGeneratedEntry; import com.virtuslab.gitmachete.frontend.file.quickfix.CreateBranchQuickFix; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod({GitMacheteBundle.class, MacheteFileUtils.class}) public class MacheteAnnotator implements Annotator, DumbAware { private boolean cantGetBranchesMessageWasShown = false; @Override @UIThreadUnsafe public void annotate(PsiElement element, AnnotationHolder holder) { if (element instanceof MacheteGeneratedEntry macheteGeneratedEntry) { processMacheteGeneratedEntry(macheteGeneratedEntry, holder); } else if (element.getNode().getElementType().equals(MacheteGeneratedElementTypes.INDENTATION)) { processIndentationElement(element, holder); } } @UIEffect private void showCantGetBranchesMessage(PsiFile file) { Editor currentEditor = FileEditorManager.getInstance(file.getProject()).getSelectedTextEditor(); if (currentEditor == null) { return; } HintManager.getInstance().showInformationHint(currentEditor, getString("string.GitMachete.MacheteAnnotator.could-not-retrieve-local-branches"), HintManager.ABOVE); cantGetBranchesMessageWasShown = true; } @UIThreadUnsafe private void processMacheteGeneratedEntry(MacheteGeneratedEntry macheteEntry, AnnotationHolder holder) { MacheteGeneratedBranch branch = macheteEntry.getBranch(); PsiFile file = macheteEntry.getContainingFile(); val branchNames = file.getBranchNamesForPsiMacheteFile(); if (branchNames.isEmpty()) { if (!cantGetBranchesMessageWasShown) { ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> showCantGetBranchesMessage(file)); } return; } cantGetBranchesMessageWasShown = false; String processedBranchName = branch.getText(); // update the state of the .git/machete VirtualFile so that new entry is available in the VirtualFile ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> MacheteFileUtils.saveDocument(file)); /* * Check for duplicate entries in the machete file. Note: there's no guarantee that at the point when * isBranchNameRepeated(branchLayoutReader, file, processedBranchName) is invoked, saveDocument(file) is already completed. * UI thread might be busy with other operations, and it might take while for the execution of saveDocument(file) to start. */ val branchLayoutReader = ApplicationManager.getApplication().getService(IBranchLayoutReader.class); try { if (isBranchNameRepeated(branchLayoutReader, file, processedBranchName)) { holder.newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.branch-entry-already-defined").fmt(processedBranchName)) .range(branch).create(); } } catch (PluginException | IllegalStateException ignored) { // ignore dubious IDE checks against annotation range } if (!branchNames.contains(processedBranchName)) { val parentBranchName = getParentBranchName(branchLayoutReader, file, processedBranchName); val basicAnnotationBuilder = holder .newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.cannot-find-local-branch-in-repo").fmt(processedBranchName)) .range(branch); if (parentBranchName == null) { // do not suggest creating a new root branch basicAnnotationBuilder.create(); } else { // suggest creating a new branch from the parent branch GitRepository gitRepository = MacheteFileUtils.findGitRepositoryForPsiMacheteFile(file); basicAnnotationBuilder.withFix(new CreateBranchQuickFix(processedBranchName, parentBranchName, file, gitRepository)) .create(); } } } private boolean isBranchNameRepeated(IBranchLayoutReader branchLayoutReader, PsiFile file, String branchName) { BranchLayout branchLayout; try { branchLayout = ReadAction.<BranchLayout, BranchLayoutException>compute( () -> MacheteFileReader.readBranchLayout(Path.of(file.getVirtualFile().getPath()), branchLayoutReader)); } catch (BranchLayoutException e) { // might appear if branchLayout has inconsistent indentation characters or file is inaccessible return false; } return branchLayout.isEntryDuplicated(branchName); } private @Nullable String getParentBranchName(IBranchLayoutReader branchLayoutReader, PsiFile file, String branchName) { BranchLayout branchLayout; try { branchLayout = ReadAction.<BranchLayout, BranchLayoutException>compute( () -> MacheteFileReader.readBranchLayout(Path.of(file.getVirtualFile().getPath()), branchLayoutReader)); } catch (BranchLayoutException e) { // might appear if branchLayout has inconsistent indentation characters or file is inaccessible return null; } val entry = branchLayout.getEntryByName(branchName); if (entry == null) { // might happen if saveDocument(file) has not completed yet return null; } val parentEntry = entry.getParent(); if (parentEntry == null) { return null; } return parentEntry.getName(); } private void processIndentationElement(PsiElement element, AnnotationHolder holder) { PsiElement parent = element.getParent(); assert parent != null : "Element has no parent"; if (parent instanceof MacheteFile) { return; } val prevMacheteGeneratedEntryOption = getPrevSiblingMacheteGeneratedEntry(parent); if (prevMacheteGeneratedEntryOption == null) { holder .newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.cannot-indent-first-entry")) .range(element).create(); return; } int prevLevel; int thisLevel; boolean hasPrevLevelCorrectWidth; IndentationParameters indentationParameters = findIndentationParameters(element); val prevIndentationNodeOption = getIndentationNodeFromMacheteGeneratedEntry(prevMacheteGeneratedEntryOption); if (prevIndentationNodeOption == null) { prevLevel = 0; hasPrevLevelCorrectWidth = true; } else { val prevIndentationText = prevIndentationNodeOption.getText(); hasPrevLevelCorrectWidth = prevIndentationText.length() % indentationParameters.indentationWidth == 0; prevLevel = prevIndentationText.length() / indentationParameters.indentationWidth; } val thisIndentationText = element.getText(); OptionalInt wrongIndentChar = thisIndentationText.chars().filter(c -> c != indentationParameters.indentationCharacter) .findFirst(); if (wrongIndentChar.isPresent()) { holder.newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.indent-char-not-match") .fmt(indentCharToName((char) wrongIndentChar.getAsInt()), indentCharToName(indentationParameters.indentationCharacter))) .range(element).create(); return; } if (thisIndentationText.length() % indentationParameters.indentationWidth != 0) { holder .newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.indent-width-not-match") .fmt(String.valueOf(indentationParameters.indentationWidth))) .range(element).create(); } thisLevel = thisIndentationText.length() / indentationParameters.indentationWidth; if (hasPrevLevelCorrectWidth && thisLevel > prevLevel + 1) { holder.newAnnotation(HighlightSeverity.ERROR, getNonHtmlString("string.GitMachete.MacheteAnnotator.too-much-indent")) .range(element).create(); } } private IndentationParameters findIndentationParameters(PsiElement currentElement) { MacheteGeneratedEntry element = getFirstMacheteGeneratedEntry(currentElement); while (element != null && getIndentationNodeFromMacheteGeneratedEntry(element) == null) { element = getNextSiblingMacheteGeneratedEntry(element); } if (element == null) { // Default - theoretically this should never happen return new IndentationParameters(' ', 4); } val indentationNodeOption = getIndentationNodeFromMacheteGeneratedEntry(element); if (indentationNodeOption == null) { // Default - this also theoretically should never happen return new IndentationParameters(' ', 4); } val indentationText = indentationNodeOption.getText(); @SuppressWarnings("index") // Indentation text is never empty (otherwise element does not exist) char indentationChar = indentationText.charAt(0); int indentationWidth = indentationText.length(); return new IndentationParameters(indentationChar, indentationWidth); } private @Nullable ASTNode getIndentationNodeFromMacheteGeneratedEntry(MacheteGeneratedEntry macheteEntry) { return macheteEntry.getNode().findChildByType(MacheteGeneratedElementTypes.INDENTATION); } private @Nullable MacheteGeneratedEntry getFirstMacheteGeneratedEntry(PsiElement currentElement) { PsiElement root = currentElement; while (root.getParent() != null) { root = root.getParent(); } return getNextSiblingMacheteGeneratedEntry(root.getFirstChild()); } private @Nullable MacheteGeneratedEntry getNextSiblingMacheteGeneratedEntry(PsiElement currentElement) { PsiElement nextSiblingMacheteGeneratedEntry = currentElement.getNextSibling(); while (nextSiblingMacheteGeneratedEntry != null && !(nextSiblingMacheteGeneratedEntry instanceof MacheteGeneratedEntry)) { nextSiblingMacheteGeneratedEntry = nextSiblingMacheteGeneratedEntry.getNextSibling(); } if (nextSiblingMacheteGeneratedEntry == null || !(nextSiblingMacheteGeneratedEntry instanceof MacheteGeneratedEntry)) { return null; } return (MacheteGeneratedEntry) nextSiblingMacheteGeneratedEntry; } private @Nullable MacheteGeneratedEntry getPrevSiblingMacheteGeneratedEntry(PsiElement currentElement) { PsiElement prevSiblingMacheteGeneratedEntry = currentElement.getPrevSibling(); while (prevSiblingMacheteGeneratedEntry != null && !(prevSiblingMacheteGeneratedEntry instanceof MacheteGeneratedEntry)) { prevSiblingMacheteGeneratedEntry = prevSiblingMacheteGeneratedEntry.getPrevSibling(); } if (prevSiblingMacheteGeneratedEntry == null || !(prevSiblingMacheteGeneratedEntry instanceof MacheteGeneratedEntry)) { return null; } return (MacheteGeneratedEntry) prevSiblingMacheteGeneratedEntry; } private String indentCharToName(char indentChar) { if (indentChar == ' ') { return "SPACE"; } else if (indentChar == '\t') { return "TAB"; } else { return "ASCII " + (int) indentChar; } } @Data private static class IndentationParameters { private final char indentationCharacter; private final int indentationWidth; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteSyntaxHighlighter.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteSyntaxHighlighter.java
package com.virtuslab.gitmachete.frontend.file.highlighting; import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteGeneratedElementTypes; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteLexerAdapter; public class MacheteSyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey BAD_CHARACTER = createTextAttributesKey("MACHETE_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER); public static final TextAttributesKey PREFIX = createTextAttributesKey("MACHETE_PREFIX", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey NAME = createTextAttributesKey("MACHETE_NAME", DefaultLanguageHighlighterColors.CLASS_NAME); public static final TextAttributesKey CUSTOM_ANNOTATION = createTextAttributesKey("MACHETE_CUSTOM_ANNOTATION", DefaultLanguageHighlighterColors.LINE_COMMENT); private static final TextAttributesKey[] BAD_CHARACTER_KEYS = new TextAttributesKey[]{BAD_CHARACTER}; private static final TextAttributesKey[] PREFIX_KEYS = new TextAttributesKey[]{PREFIX}; private static final TextAttributesKey[] NAME_KEYS = new TextAttributesKey[]{NAME}; private static final TextAttributesKey[] CUSTOM_ANNOTATION_KEYS = new TextAttributesKey[]{CUSTOM_ANNOTATION}; private static final TextAttributesKey[] EMPTY_KEYS = new TextAttributesKey[0]; @Override public Lexer getHighlightingLexer() { return new MacheteLexerAdapter(); } @Override public TextAttributesKey[] getTokenHighlights(IElementType tokenType) { return Match(tokenType).of( Case($(MacheteGeneratedElementTypes.PREFIX), PREFIX_KEYS), Case($(MacheteGeneratedElementTypes.NAME), NAME_KEYS), Case($(MacheteGeneratedElementTypes.CUSTOM_ANNOTATION), CUSTOM_ANNOTATION_KEYS), Case($(TokenType.BAD_CHARACTER), BAD_CHARACTER_KEYS), Case($(), EMPTY_KEYS)); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteColorSettingsPane.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/highlighting/MacheteColorSettingsPane.java
package com.virtuslab.gitmachete.frontend.file.highlighting; import javax.swing.Icon; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.gitmachete.frontend.file.MacheteFileUtils; import com.virtuslab.gitmachete.frontend.icons.MacheteIcons; public class MacheteColorSettingsPane implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Branch prefix", MacheteSyntaxHighlighter.PREFIX), new AttributesDescriptor("Branch name", MacheteSyntaxHighlighter.NAME), new AttributesDescriptor("Custom annotation", MacheteSyntaxHighlighter.CUSTOM_ANNOTATION), new AttributesDescriptor("Bad value", MacheteSyntaxHighlighter.BAD_CHARACTER) }; @Override public Icon getIcon() { return MacheteIcons.MACHETE_FILE; } @Override public SyntaxHighlighter getHighlighter() { return new MacheteSyntaxHighlighter(); } @Override public String getDemoText() { return MacheteFileUtils.getSampleMacheteFileContents(); } @Override public java.util.@Nullable Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @Override public String getDisplayName() { return "Git Machete"; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/codestyle/MacheteLanguageCodeStyleSettingsProvider.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/codestyle/MacheteLanguageCodeStyleSettingsProvider.java
package com.virtuslab.gitmachete.frontend.file.codestyle; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.application.options.SmartIndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import com.virtuslab.gitmachete.frontend.file.MacheteFileUtils; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteLanguage; public class MacheteLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { @Override public Language getLanguage() { return MacheteLanguage.instance; } @Override protected void customizeDefaults(CommonCodeStyleSettings commonSettings, CommonCodeStyleSettings.IndentOptions indentOptions) { indentOptions.USE_TAB_CHARACTER = true; indentOptions.TAB_SIZE = 4; indentOptions.INDENT_SIZE = indentOptions.TAB_SIZE; indentOptions.KEEP_INDENTS_ON_EMPTY_LINES = false; commonSettings.KEEP_BLANK_LINES_IN_CODE = 1; } @Override public void customizeSettings(CodeStyleSettingsCustomizable consumer, SettingsType settingsType) { if (settingsType == SettingsType.INDENT_SETTINGS) { consumer.showStandardOptions("USE_TAB_CHARACTER", "TAB_SIZE", "INDENT_SIZE", "KEEP_INDENTS_ON_EMPTY_LINES"); } else if (settingsType == SettingsType.BLANK_LINES_SETTINGS) { consumer.showStandardOptions("KEEP_BLANK_LINES_IN_CODE"); } } @Override public IndentOptionsEditor getIndentOptionsEditor() { return new SmartIndentOptionsEditor(this); } @Override public String getCodeSample(SettingsType settingsType) { return MacheteFileUtils.getSampleMacheteFileContents(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/codestyle/MacheteCodeStyleSettingsProvider.java
frontend/file/src/main/java/com/virtuslab/gitmachete/frontend/file/codestyle/MacheteCodeStyleSettingsProvider.java
package com.virtuslab.gitmachete.frontend.file.codestyle; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CodeStyleConfigurable; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsProvider; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.gitmachete.frontend.file.grammar.MacheteLanguage; public class MacheteCodeStyleSettingsProvider extends CodeStyleSettingsProvider { @Override public CodeStyleConfigurable createConfigurable(CodeStyleSettings settings, CodeStyleSettings modelSettings) { return new CodeStyleAbstractConfigurable(settings, modelSettings, this.getConfigurableDisplayName()) { @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) { return new MacheteCodeStyleMainPanel(getCurrentSettings(), settings); } }; } @Override public Language getLanguage() { return MacheteLanguage.instance; } @Override public String getConfigurableDisplayName() { return getLanguage().getDisplayName(); } private static class MacheteCodeStyleMainPanel extends TabbedLanguageCodeStylePanel { @UIEffect MacheteCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) { super(MacheteLanguage.instance, currentSettings, settings); } @Override @UIEffect protected void initTabs(CodeStyleSettings settings) { addIndentOptionsTab(settings); addBlankLinesTab(settings); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/resourcebundles/GitMacheteBundlePropertiesTestSuite.java
frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/resourcebundles/GitMacheteBundlePropertiesTestSuite.java
package com.virtuslab.gitmachete.frontend.resourcebundles; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import java.util.Properties; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; public class GitMacheteBundlePropertiesTestSuite { private static final String macheteBundleProperties = "GitMacheteBundle.properties"; @SneakyThrows private static Properties loadProperties() { Properties properties = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); properties.load(loader.getResourceAsStream(macheteBundleProperties)); return properties; } @Test public void html_properties_should_have_correct_syntax() { Properties properties = loadProperties(); properties.entrySet().stream() .filter(prop -> ((String) prop.getValue()).contains("<")) .forEach(t -> { String key = (String) t.getKey(); String value = (String) t.getValue(); assertEquals("<html>", value.substring(0, 6), "HTML property should start with <html> (key=${key})"); assertEquals("</html>", value.substring(value.length() - 7), "HTML property should end with </html> (key=${key})"); assertEquals(".HTML", key.substring(key.length() - 5), "HTML property key should have a .HTML suffix (key=${key})"); }); } @Test public void properties_should_have_no_double_quote_wrapping() { Properties properties = loadProperties(); properties.forEach((keyObj, valueObj) -> { String key = (String) keyObj; String value = (String) valueObj; assertFalse(value.endsWith("\"") && value.startsWith("\""), "Key '${key}' has value wrapped in double quotes (\"). Remove unnecessary wrapping"); }); } @Test public void properties_should_contain_only_valid_single_quotes() { Properties properties = loadProperties(); properties.forEach((keyObj, valueObj) -> { String key = (String) keyObj; String value = (String) valueObj; assertFalse(value.matches(".*\\{\\d+}.*") && value.matches("^'[^'].*|.*[^']'[^'].*|.*[^']'$"), "Key '${key}' has a format element ({number}), but contains a single apostrophe (')." + "Use a double apostrophe ('') instead"); assertFalse(!value.matches(".*\\{\\d+}.*") && value.matches(".*''.*"), "Key '${key}' has NO format element ({number}), but contains a double apostrophe ('')." + "Use a single apostrophe (') instead"); }); } @Test public void properties_should_use_ellipsis_instead_of_three_dots() { Properties properties = loadProperties(); properties.entrySet().stream() .filter(prop -> ((String) prop.getValue()).contains("...")) .forEach(t -> { String key = (String) t.getKey(); fail("Properties should use ellipsis (\\u2026) instead of three dots (key=${key})"); }); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/errorreport/GitMacheteErrorReportSubmitterTest.java
frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/errorreport/GitMacheteErrorReportSubmitterTest.java
package com.virtuslab.gitmachete.frontend.errorreport; import static com.virtuslab.gitmachete.frontend.errorreport.GitMacheteErrorReportSubmitter.MAX_GITHUB_URI_LENGTH; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; import lombok.SneakyThrows; import lombok.val; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class GitMacheteErrorReportSubmitterTest { private GitMacheteErrorReportSubmitter reportSubmitter; @BeforeEach public void setUp() { reportSubmitter = new GitMacheteErrorReportSubmitter(new DummyPlatformInfoProvider()); } private StackTraceElement[] getMockStackTrace(int stackLength) { val stackTraceElement = new StackTraceElement("com.virtuslab.DeclaringClass", "someMethod", "DeclaringClass.java", /* lineNumber */ 1234); val stackTrace = new StackTraceElement[stackLength]; Arrays.fill(stackTrace, stackTraceElement); return stackTrace; } private IdeaLoggingEvent getMockEvent(String exceptionMessage, int stackLength) { val exception = new RuntimeException(exceptionMessage); exception.setStackTrace(getMockStackTrace(stackLength)); return new IdeaLoggingEvent("some message", exception); } private Exception getWrappedExceptions(Exception wrappedException, int exceptionNumber) { if (exceptionNumber == 0) return wrappedException; val furtherWrappedException = new RuntimeException("WrappedExceptionMessage", wrappedException); furtherWrappedException.setStackTrace(getMockStackTrace(30 + 2 * exceptionNumber)); return getWrappedExceptions(furtherWrappedException, exceptionNumber - 1); } private IdeaLoggingEvent getWrappedExceptionsEvent(int exceptionNumber) { val rootCauseException = new RuntimeException("RootCauseMessage"); rootCauseException.setStackTrace(getMockStackTrace(55)); return new IdeaLoggingEvent("some message", getWrappedExceptions(rootCauseException, exceptionNumber)); } private IdeaLoggingEvent getSuppressedExceptionsEvent() { val suppressedException1 = new RuntimeException("SuppressedExceptionMessage"); suppressedException1.setStackTrace(getMockStackTrace(63)); val suppressedException2 = new RuntimeException("SuppressedExceptionMessage"); suppressedException2.setStackTrace(getMockStackTrace(68)); val exception = new RuntimeException("ExceptionMessage"); exception.setStackTrace(getMockStackTrace(57)); exception.addSuppressed(suppressedException1); exception.addSuppressed(suppressedException2); return new IdeaLoggingEvent("some message", exception); } @SneakyThrows private static String expectedUri(String baseName) { return IOUtils.resourceToString("/expected-error-report-uris/${baseName}.txt", StandardCharsets.UTF_8).replace("\n", ""); } @Test public void shouldConstructUriWithoutStackTrace() throws Exception { val event0 = getMockEvent("exception message", 0); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event0}, /* additionalInfo */ null); assertEquals(expectedUri("without_stack_trace"), uri.toString()); } @Test public void shouldConstructUriWithStackTrace() throws Exception { val event10 = getMockEvent("exception message", 10); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event10}, /* additionalInfo */ null); assertEquals(expectedUri("with_stack_trace"), uri.toString()); } @Test public void shouldConstructUriForMultipleEvents() throws Exception { val event0 = getMockEvent("exception message", 0); val event10 = getMockEvent("another exception message", 10); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event0, event10}, /* additionalInfo */ null); assertEquals(expectedUri("for_multiple_events"), uri.toString()); } @Test public void shouldShortenWrappedExceptionStacktrace() throws Exception { val event = getWrappedExceptionsEvent(5); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event}, /* additionalInfo */ null); assertEquals(expectedUri("with_wrapped_exceptions"), uri.toString()); } @Test public void shouldShortenSuppressedExceptionStacktrace() throws Exception { val event = getSuppressedExceptionsEvent(); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event}, /* additionalInfo */ null); assertEquals(expectedUri("with_suppressed_exceptions"), uri.toString()); } @Test public void shouldNotConstructUriLongerThanGitHubLimit() throws Exception { val event = getMockEvent("exception message", 1000); URI uri = reportSubmitter.constructNewGitHubIssueUri(new IdeaLoggingEvent[]{event}, /* additionalInfo */ null); assertEquals(expectedUri("long_uri"), uri.toString()); assertTrue(uri.toString().length() <= MAX_GITHUB_URI_LENGTH, "URI is longer than ${MAX_GITHUB_URI_LENGTH} bytes"); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/errorreport/DummyPlatformInfoProvider.java
frontend/base/src/test/java/com/virtuslab/gitmachete/frontend/errorreport/DummyPlatformInfoProvider.java
package com.virtuslab.gitmachete.frontend.errorreport; class DummyPlatformInfoProvider extends PlatformInfoProvider { @Override String getOSName() { return "Mock OS X"; } @Override String getOSVersion() { return "Hehe"; } @Override String getIdeApplicationName() { return "mocked IntelliJ idea"; } @Override String getPluginVersion() { return "mock plugin version"; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionGroupIds.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionGroupIds.java
package com.virtuslab.gitmachete.frontend.defs; public final class ActionGroupIds { private ActionGroupIds() {} public static final String CONTEXT_MENU = "GitMachete.ContextMenu"; public static final String TOOLBAR = "GitMachete.Toolbar"; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/GitConfigKeys.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/GitConfigKeys.java
package com.virtuslab.gitmachete.frontend.defs; public final class GitConfigKeys { private GitConfigKeys() {} public static final String DELETE_LOCAL_BRANCH_ON_SLIDE_OUT = "machete.slideOut.deleteLocalBranch"; public static String overrideForkPointToKey(String branchName) { return "machete.overrideForkPoint.${branchName}.to"; } public static String overrideForkPointWhileDescendantOf(String branchName) { return "machete.overrideForkPoint.${branchName}.whileDescendantOf"; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/PropertiesComponentKeys.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/PropertiesComponentKeys.java
package com.virtuslab.gitmachete.frontend.defs; public final class PropertiesComponentKeys { private PropertiesComponentKeys() {} public static final String SHOW_MERGE_WARNING = "git-machete.merge.warning.show"; public static final String SHOW_RESET_INFO = "git-machete.reset.info.show"; public static final String SHOW_TRAVERSE_INFO = "git-machete.traverse.approval.show"; public static final String SHOW_UNMANAGED_BRANCH_NOTIFICATION = "git-machete.unmanaged.notification.show"; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/Colors.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/Colors.java
package com.virtuslab.gitmachete.frontend.defs; import java.awt.Color; import com.intellij.ui.JBColor; public final class Colors { private Colors() {} private static final Color RED_COLOR = Color.decode("#FF0000"); private static final Color ORANGE_COLOR = Color.decode("#FDA909"); private static final Color DARK_ORANGE_COLOR = Color.decode("#D68C00"); private static final Color YELLOW_COLOR = Color.decode("#C4A000"); private static final Color GREEN_COLOR = Color.decode("#008000"); private static final Color GRAY_COLOR = Color.decode("#BBBBBB"); private static final Color DARK_GREY_COLOR = Color.decode("#888888"); private static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, /* alpha */ 0); /** * {@link JBColor} are pairs of colors for light and dark IDE theme. LHS colors names are their * "general" description. They may differ from RHS (which are actual and specific colors). */ public static final JBColor RED = new JBColor(RED_COLOR, RED_COLOR); public static final JBColor ORANGE = new JBColor(DARK_ORANGE_COLOR, ORANGE_COLOR); public static final JBColor YELLOW = new JBColor(YELLOW_COLOR, YELLOW_COLOR); public static final JBColor GREEN = new JBColor(GREEN_COLOR, GREEN_COLOR); public static final JBColor GRAY = new JBColor(DARK_GREY_COLOR, GRAY_COLOR); public static final JBColor TRANSPARENT = new JBColor(TRANSPARENT_COLOR, TRANSPARENT_COLOR); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionIds.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionIds.java
package com.virtuslab.gitmachete.frontend.defs; public final class ActionIds { private ActionIds() {} public static final String CHECK_OUT_SELECTED = "GitMachete.CheckoutSelectedAction"; public static final String OPEN_MACHETE_FILE = "GitMachete.OpenMacheteFileAction"; public static final String SLIDE_IN_UNMANAGED_BELOW = "GitMachete.SlideInUnmanagedBelowAction"; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/FileTypeIds.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/FileTypeIds.java
package com.virtuslab.gitmachete.frontend.defs; public final class FileTypeIds { private FileTypeIds() {} // Extracted so that frontend:ui doesn't need to depend on frontend:file. public static final String NAME = "Machete File"; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionPlaces.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/defs/ActionPlaces.java
package com.virtuslab.gitmachete.frontend.defs; public final class ActionPlaces { private ActionPlaces() {} public static final String CONTEXT_MENU = "GitMacheteContextMenu"; public static final String TOOLBAR = "GitMacheteToolbar"; public static final String VCS_NOTIFICATION = "Vcs.Notification"; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/icons/MacheteIcons.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/icons/MacheteIcons.java
package com.virtuslab.gitmachete.frontend.icons; import javax.swing.Icon; import com.intellij.openapi.util.IconLoader; public final class MacheteIcons { private MacheteIcons() {} public static final Icon LOGO = loadIcon("macheteLogoIcon32"); public static final Icon DISCOVER = loadIcon("macheteLogoIcon"); public static final Icon EDIT = loadIcon("edit"); public static final Icon FAST_FORWARD = loadIcon("fastForward"); public static final Icon FETCH = loadIcon("fetch"); public static final Icon HELP = loadIcon("help"); public static final Icon MACHETE_FILE = loadIcon("macheteLogoIcon"); public static final Icon MERGE_PARENT = loadIcon("merge"); public static final Icon OVERRIDE_FORK_POINT = loadIcon("overrideForkPoint"); public static final Icon PULL = loadIcon("pull"); public static final Icon PUSH = loadIcon("push"); public static final Icon REBASE = loadIcon("rebase"); public static final Icon RENAME = loadIcon("rename"); public static final Icon RESET = loadIcon("reset"); public static final Icon SLIDE_IN = loadIcon("slideIn"); public static final Icon SLIDE_OUT = loadIcon("slideOut"); public static final Icon SQUASH = loadIcon("squash"); public static final Icon TOGGLE_LISTING_COMMITS = loadIcon("toggleListingCommits"); public static final Icon TRAVERSE = loadIcon("traverse"); private static Icon loadIcon(String basename) { return IconLoader.getIcon("/icons/${basename}.svg", MacheteIcons.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/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/common/WriteActionUtils.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/common/WriteActionUtils.java
package com.virtuslab.gitmachete.frontend.common; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.WriteAction; import com.intellij.util.ThrowableRunnable; import lombok.SneakyThrows; import org.checkerframework.checker.guieffect.qual.UI; import org.checkerframework.checker.guieffect.qual.UIEffect; public final class WriteActionUtils { private WriteActionUtils() {} // We don't provide asynchronous (non-blocking) variant since it turned out prone to race conditions. public static <E extends Throwable> void blockingRunWriteActionOnUIThread(@UI ThrowableRunnable<E> action) { ApplicationManager.getApplication().invokeAndWait(getWriteActionRunnable(action)); } private static <E extends Throwable> @UI Runnable getWriteActionRunnable(@UI ThrowableRunnable<E> action) { return new @UI Runnable() { @Override @SneakyThrows @UIEffect public void run() { WriteAction.run(action); } }; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/resourcebundles/GitMacheteBundle.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/resourcebundles/GitMacheteBundle.java
package com.virtuslab.gitmachete.frontend.resourcebundles; import java.text.MessageFormat; import java.util.ResourceBundle; import org.checkerframework.checker.i18nformatter.qual.I18nFormatFor; import org.checkerframework.checker.i18nformatter.qual.I18nMakeFormat; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.tainting.qual.PolyTainted; import org.checkerframework.checker.tainting.qual.Untainted; import org.checkerframework.common.value.qual.MinLen; import org.jetbrains.annotations.PropertyKey; public final class GitMacheteBundle { public static final String BUNDLE = "GitMacheteBundle"; private static final ResourceBundle instance = ResourceBundle.getBundle(BUNDLE); private GitMacheteBundle() {} /** * A more restrictive version of {@link MessageFormat#format(String, Object...)}. * Since each parameter must be a non-null {@link String}, * we can capture the unintended parameter types (like {@code io.vavr.control.Option}) more easily during the build * (this is realized with ArchUnit; see the test against {@code Option#toString} in the top-level project). * Note that we consciously use the name "fmt" instead of "format" * to avoid an accidental use of {@link String#format(String, Object...)} * and emphasize the need to use the {@link lombok.experimental.ExtensionMethod} annotation. * * @param format as in {@link MessageFormat#format(String, Object...)} * @param args as in {@link MessageFormat#format(String, Object...)}, * but each parameter must be a non-null {@link String} and not just a nullable {@link Object} * @return the formatted string */ public static @PolyTainted String fmt(@PolyTainted @I18nFormatFor("#2") String format, String @MinLen(1)... args) { return MessageFormat.format(format, (@Nullable Object[]) args); } @I18nMakeFormat public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) { return instance.getString(key); } @I18nMakeFormat public static @Untainted String getNonHtmlString(@PropertyKey(resourceBundle = BUNDLE) String key) { return instance.getString(key); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/errorreport/GitMacheteErrorReportSubmitter.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/errorreport/GitMacheteErrorReportSubmitter.java
package com.virtuslab.gitmachete.frontend.errorreport; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.awt.Component; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; import com.intellij.ide.BrowserUtil; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.ErrorReportSubmitter; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; import com.intellij.openapi.diagnostic.SubmittedReportInfo; import com.intellij.util.Consumer; import com.intellij.util.ModalityUiUtil; import io.vavr.collection.List; import lombok.CustomLog; import lombok.SneakyThrows; import lombok.experimental.ExtensionMethod; import lombok.val; import org.apache.commons.io.IOUtils; import org.apache.http.client.utils.URIBuilder; import org.checkerframework.checker.nullness.qual.Nullable; @CustomLog @ExtensionMethod({Arrays.class, Objects.class}) public class GitMacheteErrorReportSubmitter extends ErrorReportSubmitter { public static final int MAX_GITHUB_URI_LENGTH = 8192; private final PlatformInfoProvider platformInfoProvider; public GitMacheteErrorReportSubmitter() { this(new PlatformInfoProvider()); } GitMacheteErrorReportSubmitter(PlatformInfoProvider platformInfoProvider) { this.platformInfoProvider = platformInfoProvider; } @Override public String getReportActionText() { return getString("string.GitMachete.error-report-submitter.report-action-text"); } @Override public boolean submit( IdeaLoggingEvent[] events, @Nullable String additionalInfo, Component parentComponent, Consumer<? super SubmittedReportInfo> consumer) { try { val uri = constructNewGitHubIssueUri(events, additionalInfo); ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, () -> BrowserUtil.browse(uri)); } catch (URISyntaxException e) { LOG.error("Cannot construct URI to open new bug issue!", e); } return true; } URI constructNewGitHubIssueUri(IdeaLoggingEvent[] events, @Nullable String additionalInfo) throws URISyntaxException { val uriBuilder = new URIBuilder("https://github.com/VirtusLab/git-machete-intellij-plugin/issues/new"); String title = events.stream() .map(event -> { if (event.getThrowable() != null) { return event.getThrowableText().lines().findFirst().orElse("").stripTrailing(); } val message = event.getMessage(); return message != null ? message.stripTrailing() : ""; }) .collect(Collectors.joining("; ")); uriBuilder.setParameter("title", title); uriBuilder.setParameter("labels", "bug"); URI uri; List<String> reportBodyLines = List.ofAll(getReportBody(events, additionalInfo).lines()) .append("<placeholder-for-do-while>"); do { // Let's cut the body gradually line-by-line until the resulting URI fits into the GitHub limits. // It's hard to predict the perfect exact cut in advance due to URL encoding. reportBodyLines = reportBodyLines.dropRight(1); uriBuilder.setParameter("body", reportBodyLines.mkString(System.lineSeparator())); uri = uriBuilder.build(); } while (uri.toString().length() > MAX_GITHUB_URI_LENGTH); return uri; } private String getReportBody( IdeaLoggingEvent[] events, @Nullable String additionalInfo) { String reportBody = getBugTemplate(); for (java.util.Map.Entry<String, String> entry : getTemplateVariables(events, additionalInfo).entrySet()) { reportBody = reportBody.replace("%${entry.getKey()}%", entry.getValue()); } return reportBody; } // An error (from a typo in resource name) will be captured by the tests. @SneakyThrows private String getBugTemplate() { return IOUtils.resourceToString("/bug_report.md", StandardCharsets.UTF_8); } private java.util.Map<String, String> getTemplateVariables( IdeaLoggingEvent[] events, @Nullable String additionalInfo) { val templateVariables = new java.util.HashMap<String, String>(); templateVariables.put("ide", platformInfoProvider.getIdeApplicationName()); val pluginVersion = platformInfoProvider.getPluginVersion().requireNonNullElse("<unknown>"); templateVariables.put("macheteVersion", pluginVersion); val osName = platformInfoProvider.getOSName().requireNonNullElse(""); val osVersion = platformInfoProvider.getOSVersion().requireNonNullElse(""); templateVariables.put("os", osName + " " + osVersion); templateVariables.put("additionalInfo", additionalInfo.requireNonNullElse("N/A")); val nl = System.lineSeparator(); String stacktraces = events.stream() .map(event -> { // This message is distinct from the throwable's message: // in `LOG.error(message, throwable)`, it's the first parameter. val messagePart = event.getMessage() != null ? (event.getMessage() + nl + nl) : ""; val throwablePart = shortenExceptionsStack(event.getThrowableText().stripTrailing()); return "```${nl}${messagePart}${throwablePart}${nl}```"; }) .collect(Collectors.joining("${nl}${nl}")); templateVariables.put("stacktraces", stacktraces); return templateVariables; } private String shortenExceptionsStack(String stackTrace) { val nl = System.lineSeparator(); val rootCauseIndex = Math.max( stackTrace.lastIndexOf("Caused by:"), stackTrace.lastIndexOf("\tSuppressed:")); if (rootCauseIndex != -1) { val rootCauseStackTrace = stackTrace.substring(rootCauseIndex); val lines = stackTrace.substring(0, rootCauseIndex).split(nl); StringBuilder resultString = new StringBuilder(); for (int i = 0; i < lines.length; i++) { if (lines[i].contains("Caused by:") || lines[i].contains("Suppressed:") || i == 0) { resultString.append(lines[i]).append(nl); if (i + 1 < lines.length) { resultString.append("${lines[i+1]}...").append(nl); } } } return resultString.append(rootCauseStackTrace).toString(); } return stackTrace; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/errorreport/PlatformInfoProvider.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/errorreport/PlatformInfoProvider.java
package com.virtuslab.gitmachete.frontend.errorreport; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.extensions.PluginId; import org.apache.commons.lang3.SystemUtils; import org.checkerframework.checker.nullness.qual.Nullable; class PlatformInfoProvider { @Nullable String getOSName() { return SystemUtils.OS_NAME; } @Nullable String getOSVersion() { return SystemUtils.OS_VERSION; } String getIdeApplicationName() { return ApplicationInfo.getInstance().getFullApplicationName(); } @Nullable String getPluginVersion() { IdeaPluginDescriptor pluginDescriptor = PluginManagerCore.getPlugin(PluginId.getId("com.virtuslab.git-machete")); return pluginDescriptor != null ? pluginDescriptor.getVersion() : null; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/vfsutils/GitVfsUtils.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/vfsutils/GitVfsUtils.java
package com.virtuslab.gitmachete.frontend.vfsutils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import com.intellij.openapi.vfs.VirtualFile; import git4idea.GitUtil; import git4idea.repo.GitRepository; import lombok.extern.slf4j.Slf4j; import org.checkerframework.checker.nullness.qual.Nullable; @Slf4j public final class GitVfsUtils { private static final String MACHETE_FILE_NAME = "machete"; private GitVfsUtils() {} public static VirtualFile getMainGitDirectory(GitRepository gitRepository) { VirtualFile vfGitDir = getWorktreeGitDirectory(gitRepository); // For worktrees, the format of .git dir path is: // <repo-root>/.git/worktrees/<per-worktree-directory> // Let's detect if that's what `findGitDir` returned; // if so, let's use the top-level <repo-root>/.git dir instead. // Note that for submodules we're okay with the path returned by `findGitDir`. VirtualFile parent1 = vfGitDir.getParent(); if (parent1 != null && parent1.getName().equals("worktrees")) { VirtualFile parent2 = parent1.getParent(); if (parent2 != null && parent2.getName().equals(".git")) { return parent2; } } return vfGitDir; } public static VirtualFile getWorktreeGitDirectory(GitRepository gitRepository) { VirtualFile vfGitDir = GitUtil.findGitDir(gitRepository.getRoot()); assert vfGitDir != null : "Can't get .git directory from repo root path ${gitRepository.getRoot()}"; return vfGitDir; } public static Path getMainGitDirectoryPath(GitRepository gitRepository) { VirtualFile vfGitDir = getMainGitDirectory(gitRepository); return Paths.get(vfGitDir.getPath()); } public static Path getWorktreeGitDirectoryPath(GitRepository gitRepository) { VirtualFile vfGitDir = getWorktreeGitDirectory(gitRepository); return Paths.get(vfGitDir.getPath()); } public static Path getRootDirectoryPath(GitRepository gitRepository) { return Paths.get(gitRepository.getRoot().getPath()); } /** * @param gitRepository {@link GitRepository} to get the virtual file from * @return {@link VirtualFile} representing the machete file if found; otherwise, null */ public static @Nullable VirtualFile getMacheteFile(GitRepository gitRepository) { return getMainGitDirectory(gitRepository).findChild(MACHETE_FILE_NAME); } /** * As opposed to {@link GitVfsUtils#getMacheteFile(GitRepository)} the result always exists. * This is because the path is valid even though the file may not exist. * * @param gitRepository {@link GitRepository} to resolve the path within * @return {@link Path} representing the machete file */ public static Path getMacheteFilePath(GitRepository gitRepository) { return getMainGitDirectoryPath(gitRepository).resolve(MACHETE_FILE_NAME); } public static @Nullable Long getFileModificationEpochMillis(Path filePath) { try { BasicFileAttributes fileAttributes = Files.readAttributes(filePath, BasicFileAttributes.class); return fileAttributes.lastModifiedTime().toMillis(); } catch (IOException e) { LOG.error("Failed to get modification date of ${filePath}", e); return null; } } public static void setFileModificationEpochMillis(Path filePath, long epochMillis) { try { Files.setLastModifiedTime(filePath, FileTime.fromMillis(epochMillis)); } catch (IOException e) { LOG.error("Failed setting modification date on ${filePath}", e); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/datakeys/DataKeys.java
frontend/base/src/main/java/com/virtuslab/gitmachete/frontend/datakeys/DataKeys.java
package com.virtuslab.gitmachete.frontend.datakeys; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import com.intellij.openapi.actionSystem.DataKey; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot; public final class DataKeys { private DataKeys() {} public static final DataKey<@Nullable IGitMacheteRepositorySnapshot> GIT_MACHETE_REPOSITORY_SNAPSHOT = DataKey .create("GIT_MACHETE_REPOSITORY_SNAPSHOT"); public static final DataKey<@Nullable String> SELECTED_BRANCH_NAME = DataKey.create("SELECTED_BRANCH_NAME"); public static final DataKey<@Nullable String> UNMANAGED_BRANCH_NAME = DataKey.create("UNMANAGED_BRANCH_NAME"); // Note: this method isn't currently fully null-safe, it's possible to pass {@code null} as {@code value} // even if {@code T} is marked as {@code @NonNull}. // See https://github.com/typetools/checker-framework/issues/3289 // and generally https://github.com/typetools/checker-framework/issues/979. public static <T> Match.Case<String, T> typeSafeCase(DataKey<T> key, T value) { return Case($(key.getName()), 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/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/paint/GraphCellPainter.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/paint/GraphCellPainter.java
package com.virtuslab.gitmachete.frontend.graph.impl.paint; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.Ellipse2D; import javax.swing.JTable; import com.intellij.ui.JBColor; import io.vavr.collection.HashMap; import io.vavr.collection.List; import io.vavr.collection.Map; import lombok.RequiredArgsConstructor; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.gitmachete.frontend.defs.Colors; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.paint.IGraphCellPainter; import com.virtuslab.gitmachete.frontend.graph.api.paint.PaintParameters; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IEdgeRenderPart; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; @RequiredArgsConstructor public class GraphCellPainter implements IGraphCellPainter { private final JTable table; @UIEffect protected int getRowHeight() { val font = table.getFont(); // The font (if missing) is being retrieved from parent. In the case of parent absence it could be null. if (font != null) { // The point is to scale the graph table content (text and graph) along with the font specified by settings. return Math.max(table.getFontMetrics(font).getHeight(), table.getRowHeight()); } else { return table.getRowHeight(); } } @UIEffect private BasicStroke getOrdinaryStroke() { return new BasicStroke(PaintParameters.getLineThickness(getRowHeight()), BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL); } @UIEffect private void paintUpLine(Graphics2D g2, Color color, int posInRow) { int nodeWidth = PaintParameters.getNodeWidth(getRowHeight()); int x = nodeWidth * posInRow + nodeWidth / 2; int y1 = getRowHeight() / 2 - 1; int y2 = 0; paintLine(g2, color, x, y1, x, y2); } @UIEffect private void paintDownLine(Graphics2D g2, Color color, int posInRow) { int nodeWidth = PaintParameters.getNodeWidth(getRowHeight()); int y2 = getRowHeight(); int y1 = getRowHeight() / 2; int x = nodeWidth * posInRow + nodeWidth / 2; paintLine(g2, color, x, y1, x, y2); } @UIEffect private void paintRightLine(Graphics2D g2, Color color, int posInRow) { int nodeWidth = PaintParameters.getNodeWidth(getRowHeight()); int x1 = nodeWidth * posInRow + nodeWidth / 2; int x2 = x1 + nodeWidth; int y = getRowHeight() / 2; paintLine(g2, color, x1, y, x2, y); } @UIEffect private void paintLine(Graphics2D g2, Color color, int x1, int y1, int x2, int y2) { g2.setColor(color); g2.setStroke(getOrdinaryStroke()); g2.drawLine(x1, y1, x2, y2); } @UIEffect private void paintCircle(Graphics2D g2, int position, Color color) { int nodeWidth = PaintParameters.getNodeWidth(getRowHeight()); int x0 = nodeWidth * position + nodeWidth / 2; int y0 = getRowHeight() / 2; int r = PaintParameters.getCircleRadius(getRowHeight()); Ellipse2D.Double circle = new Ellipse2D.Double(x0 - r + 0.5, y0 - r + 0.5, 2 * r, 2 * r); g2.setColor(color); g2.fill(circle); } private static final Map<GraphItemColor, JBColor> COLORS = HashMap.of( GraphItemColor.GRAY, Colors.GRAY, GraphItemColor.YELLOW, Colors.YELLOW, GraphItemColor.RED, Colors.RED, GraphItemColor.GREEN, Colors.GREEN); @UIEffect private Color getColor(IRenderPart renderPart) { return COLORS.getOrElse(renderPart.getGraphItemColor(), Colors.TRANSPARENT); } @Override @UIEffect public void draw(Graphics2D g2, List<? extends IRenderPart> renderParts) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (IRenderPart renderPart : renderParts) { drawRenderPart(g2, renderPart); } } @UIEffect protected void drawRenderPart(Graphics2D g2, IRenderPart renderPart) { if (renderPart.isNode()) { int posInRow = renderPart.getPositionInRow(); paintCircle(g2, posInRow, getColor(renderPart)); } else { // isEdge drawEdge(g2, getColor(renderPart), renderPart.asEdge()); } } @UIEffect private void drawEdge(Graphics2D g2, Color color, IEdgeRenderPart edgeRenderPart) { int posInRow = edgeRenderPart.getPositionInRow(); if (edgeRenderPart.getType() == IEdgeRenderPart.Type.DOWN) { paintDownLine(g2, color, posInRow); } else if (edgeRenderPart.getType() == IEdgeRenderPart.Type.UP) { paintUpLine(g2, color, posInRow); } else if (edgeRenderPart.getType() == IEdgeRenderPart.Type.RIGHT) { paintRightLine(g2, color, posInRow); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/paint/GraphCellPainterFactory.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/paint/GraphCellPainterFactory.java
package com.virtuslab.gitmachete.frontend.graph.impl.paint; import javax.swing.JTable; import com.virtuslab.gitmachete.frontend.graph.api.paint.IGraphCellPainterFactory; public class GraphCellPainterFactory implements IGraphCellPainterFactory { @Override public GraphCellPainter create(JTable table) { return new GraphCellPainter(table); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraphBuilder.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraphBuilder.java
package com.virtuslab.gitmachete.frontend.graph.impl.repository; import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSync; import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSyncButForkPointOff; import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.MergedToParent; import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.OutOfSync; import static com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor.GRAY; import static com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor.GREEN; import static com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor.RED; import static com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor.TRANSPARENT; import static com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor.YELLOW; import java.util.ArrayList; import java.util.Collections; import com.intellij.util.SmartList; import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.HashMap; import io.vavr.collection.List; import io.vavr.collection.Map; import lombok.Setter; import lombok.experimental.Accessors; import lombok.val; import org.checkerframework.checker.index.qual.GTENegativeOne; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch; import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot; import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot; import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot; import com.virtuslab.gitmachete.backend.api.IRootManagedBranchSnapshot; import com.virtuslab.gitmachete.backend.api.NullGitMacheteRepositorySnapshot; import com.virtuslab.gitmachete.backend.api.RelationToRemote; import com.virtuslab.gitmachete.backend.api.SyncToParentStatus; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; import com.virtuslab.gitmachete.frontend.graph.api.repository.IBranchGetCommitsStrategy; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph; import com.virtuslab.gitmachete.frontend.graph.impl.items.BranchItem; import com.virtuslab.gitmachete.frontend.graph.impl.items.CommitItem; @Accessors(fluent = true) public class RepositoryGraphBuilder { @Setter private IGitMacheteRepositorySnapshot repositorySnapshot = NullGitMacheteRepositorySnapshot.getInstance(); @Setter private IBranchGetCommitsStrategy branchGetCommitsStrategy = DEFAULT_GET_COMMITS; public static final IBranchGetCommitsStrategy DEFAULT_GET_COMMITS = INonRootManagedBranchSnapshot::getUniqueCommits; public static final IBranchGetCommitsStrategy EMPTY_GET_COMMITS = __ -> List.empty(); public IRepositoryGraph build() { Tuple2<List<IGraphItem>, List<List<Integer>>> graphData = deriveGraphItemsAndPositionsOfVisibleEdges(); return new RepositoryGraph(graphData._1(), graphData._2()); } private Tuple2<List<IGraphItem>, List<List<Integer>>> deriveGraphItemsAndPositionsOfVisibleEdges() { List<IRootManagedBranchSnapshot> rootBranches = repositorySnapshot.getRootBranches(); java.util.List<IGraphItem> graphItems = new ArrayList<>(); java.util.List<java.util.List<Integer>> positionsOfVisibleEdges = new ArrayList<>(); for (val rootBranch : rootBranches) { int currentBranchIndex = graphItems.size(); positionsOfVisibleEdges.add(Collections.emptyList()); // root branches have no visible edges addRootBranch(graphItems, rootBranch); List<? extends INonRootManagedBranchSnapshot> childBranches = rootBranch.getChildren(); recursivelyAddCommitsAndBranches(graphItems, positionsOfVisibleEdges, childBranches, currentBranchIndex, /* indentLevel */ 0); } return Tuple.of( List.ofAll(graphItems), positionsOfVisibleEdges.stream().map(List::ofAll).collect(List.collector())); } /** * @param graphItems * the collection to store child commits and branches * @param childBranches * branches to add with their commits * @param parentBranchIndex * the index of branch which child branches (with their commits) are to be added */ private void recursivelyAddCommitsAndBranches( java.util.List<IGraphItem> graphItems, java.util.List<java.util.List<Integer>> positionsOfVisibleEdges, List<? extends INonRootManagedBranchSnapshot> childBranches, @GTENegativeOne int parentBranchIndex, @NonNegative int indentLevel) { boolean isFirstBranch = true; val lastChildBranch = childBranches.size() > 0 ? childBranches.get(childBranches.size() - 1) : null; int previousBranchIndex = parentBranchIndex; for (val nonRootBranch : childBranches) { if (!isFirstBranch) { graphItems.get(previousBranchIndex).setNextSiblingItemIndex(graphItems.size()); } int prevSiblingItemIndex = graphItems.size() - 1; // We are building some non root branches here so some root branch item has been added already. assert prevSiblingItemIndex >= 0 : "There is no previous sibling node but should be"; buildCommitsAndNonRootBranch(graphItems, nonRootBranch, prevSiblingItemIndex, indentLevel); int upBranchIndex = graphItems.size() - 1; List<? extends INonRootManagedBranchSnapshot> branches = nonRootBranch.getChildren(); recursivelyAddCommitsAndBranches(graphItems, positionsOfVisibleEdges, /* child */ branches, upBranchIndex, indentLevel + 1); while (positionsOfVisibleEdges.size() < graphItems.size()) { positionsOfVisibleEdges.add(new SmartList<>()); } if (!nonRootBranch.equals(lastChildBranch)) { for (int i = upBranchIndex + 1; i < graphItems.size(); ++i) { positionsOfVisibleEdges.get(i).add(indentLevel); } } previousBranchIndex = upBranchIndex; isFirstBranch = false; } } private void addRootBranch(java.util.List<IGraphItem> graphItems, IRootManagedBranchSnapshot branch) { BranchItem branchItem = createBranchItemFor(branch, /* prevSiblingItemIndex */ -1, GraphItemColor.GREEN, /* indentLevel */ 0); graphItems.add(branchItem); } private static final Map<SyncToParentStatus, GraphItemColor> ITEM_COLORS = HashMap.of( MergedToParent, GRAY, InSyncButForkPointOff, YELLOW, OutOfSync, RED, InSync, GREEN); private static GraphItemColor getGraphItemColor(SyncToParentStatus syncToParentStatus) { return ITEM_COLORS.getOrElse(syncToParentStatus, TRANSPARENT); } private void buildCommitsAndNonRootBranch( java.util.List<IGraphItem> graphItems, INonRootManagedBranchSnapshot branch, @NonNegative int parentBranchIndex, @NonNegative int indentLevel) { List<ICommitOfManagedBranch> commits = branchGetCommitsStrategy.getCommitsOf(branch).reverse(); val syncToParentStatus = branch.getSyncToParentStatus(); GraphItemColor graphItemColor = getGraphItemColor(syncToParentStatus); int branchItemIndex = graphItems.size() + commits.size(); // We are building some non root branch here so some root branch item has been added already. assert branchItemIndex > 0 : "Branch node index is not greater than 0 but should be"; boolean isFirstItemInBranch = true; for (ICommitOfManagedBranch commit : commits) { int lastItemIndex = graphItems.size() - 1; // We are building some non root branch here so some root branch item has been added already. assert lastItemIndex >= 0 : "Last node index is less than 0 but shouldn't be"; int prevSiblingItemIndex = isFirstItemInBranch ? parentBranchIndex : lastItemIndex; int nextSiblingItemIndex = graphItems.size() + 1; val c = new CommitItem(commit, branch, graphItemColor, prevSiblingItemIndex, nextSiblingItemIndex, indentLevel); graphItems.add(c); isFirstItemInBranch = false; } int lastItemIndex = graphItems.size() - 1; /* * If a branch has no commits (possibly due to commits getting strategy being {@code EMPTY_GET_COMMITS}) its {@code * prevSiblingItemIndex} is just the {@code parentBranchIndex}. Otherwise the {@code prevSiblingItemIndex} is an index of * most recently added item (its last commit). */ int prevSiblingItemIndex = commits.isEmpty() ? parentBranchIndex : lastItemIndex; BranchItem branchItem = createBranchItemFor(branch, prevSiblingItemIndex, graphItemColor, indentLevel); graphItems.add(branchItem); } /** * @return {@link BranchItem} for given properties and provide additional attributes if the branch is the current one */ private BranchItem createBranchItemFor( IManagedBranchSnapshot branch, @GTENegativeOne int prevSiblingItemIndex, GraphItemColor graphItemColor, @NonNegative int indentLevel) { RelationToRemote relationToRemote = branch.getRelationToRemote(); val currentBranch = repositorySnapshot.getCurrentBranchIfManaged(); boolean isCurrentBranch = currentBranch != null && currentBranch.equals(branch); boolean hasChildItem = !branch.getChildren().isEmpty(); return new BranchItem(branch, graphItemColor, relationToRemote, prevSiblingItemIndex, indentLevel, isCurrentBranch, hasChildItem); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraphCache.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraphCache.java
package com.virtuslab.gitmachete.frontend.graph.impl.repository; import org.checkerframework.checker.interning.qual.FindDistinct; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraphCache; public class RepositoryGraphCache implements IRepositoryGraphCache { private @MonotonicNonNull IRepositoryGraph repositoryGraphWithCommits = null; private @MonotonicNonNull IRepositoryGraph repositoryGraphWithoutCommits = null; private @MonotonicNonNull IGitMacheteRepositorySnapshot repositorySnapshot = null; @Override @SuppressWarnings("regexp") // to allow for `synchronized` public synchronized IRepositoryGraph getRepositoryGraph( @FindDistinct IGitMacheteRepositorySnapshot givenRepositorySnapshot, boolean isListingCommits) { if (givenRepositorySnapshot != this.repositorySnapshot || repositoryGraphWithCommits == null || repositoryGraphWithoutCommits == null) { this.repositorySnapshot = givenRepositorySnapshot; RepositoryGraphBuilder repositoryGraphBuilder = new RepositoryGraphBuilder().repositorySnapshot(givenRepositorySnapshot); repositoryGraphWithCommits = repositoryGraphBuilder .branchGetCommitsStrategy(RepositoryGraphBuilder.DEFAULT_GET_COMMITS).build(); repositoryGraphWithoutCommits = repositoryGraphBuilder .branchGetCommitsStrategy(RepositoryGraphBuilder.EMPTY_GET_COMMITS).build(); } return isListingCommits ? repositoryGraphWithCommits : repositoryGraphWithoutCommits; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraph.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/repository/RepositoryGraph.java
package com.virtuslab.gitmachete.frontend.graph.impl.repository; import com.intellij.util.SmartList; import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.List; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.initialization.qual.NotOnlyInitialized; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; import com.virtuslab.gitmachete.frontend.graph.api.render.IRenderPartGenerator; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph; import com.virtuslab.gitmachete.frontend.graph.impl.render.RenderPartGenerator; public class RepositoryGraph implements IRepositoryGraph { private final List<IGraphItem> items; private final List<List<Integer>> positionsOfVisibleEdges; @NotOnlyInitialized private final IRenderPartGenerator renderPartGenerator; public RepositoryGraph(List<IGraphItem> items, List<List<Integer>> positionsOfVisibleEdges) { this.items = items; this.positionsOfVisibleEdges = positionsOfVisibleEdges; this.renderPartGenerator = new RenderPartGenerator(/* repositoryGraph */ this); } /** * Adjacent edges are the edges that are visible in a row and directly connected to the node * (representing branch/commit item) of this row. See {@link RepositoryGraph#getVisibleEdgesWithPositions} for more details. * * @param itemIndex item index * @return list of adjacent edges in a given item index */ public List<GraphEdge> getAdjacentEdges(@NonNegative int itemIndex) { java.util.List<GraphEdge> adjacentEdges = new SmartList<>(); @SuppressWarnings("upperbound:argument") IGraphItem currentItem = items.get(itemIndex); if (itemIndex > 0) { int upNodeIndex = currentItem.getPrevSiblingItemIndex(); if (upNodeIndex >= 0) { adjacentEdges.add(GraphEdge.createEdge(/* nodeIndex1 */ itemIndex, /* nodeIndex2 */ upNodeIndex)); } } if (itemIndex < items.size() - 1) { Integer nextSiblingItemIndex = currentItem.getNextSiblingItemIndex(); if (nextSiblingItemIndex != null) { adjacentEdges.add(GraphEdge.createEdge(/* nodeIndex1 */ itemIndex, /* nodeIndex2 */ nextSiblingItemIndex)); } } return List.ofAll(adjacentEdges); } @SuppressWarnings("upperbound:argument") public IGraphItem getGraphItem(@NonNegative int itemIndex) { return items.get(itemIndex); } public @NonNegative int getNodesCount() { return items.size(); } public List<? extends IRenderPart> getRenderParts(@NonNegative int itemIndex) { return renderPartGenerator.getRenderParts(itemIndex); } /** * Visible edges are the edges that are visible in a row but are NOT directly connected to the node * (representing branch/commit item) of this row. See {@link RepositoryGraph#getAdjacentEdges} for more details. * * @param itemIndex item index * @return list of visible edges in a given item index */ @SuppressWarnings("allcheckers:type.arguments.not.inferred") public List<Tuple2<GraphEdge, @NonNegative Integer>> getVisibleEdgesWithPositions(@NonNegative int itemIndex) { assert itemIndex < positionsOfVisibleEdges.size() : "Bad itemIndex: " + itemIndex; return positionsOfVisibleEdges.get(itemIndex).map(pos -> { int upNodeIndex = itemIndex - 1; int downNodeIndex = itemIndex + 1; while (downNodeIndex < positionsOfVisibleEdges.size() && positionsOfVisibleEdges.get(downNodeIndex).contains(pos)) { downNodeIndex++; } while (upNodeIndex >= 0 && positionsOfVisibleEdges.get(upNodeIndex).contains(pos)) { upNodeIndex--; } // We can assume the following since we know that the first node (a root branch) // AND the last node (some branch, possible indented child) has no visible edges in their rows. // (The first condition is obvious. The second can be easily proved by contradiction. // Suppose that the last node, at index n has a visible edge. Any visible edge has some (branch) node // that it leads to, hence there must exist some node at index k > n being a target to the visible edge. // But n is the index of the last node. Contradiction.) assert upNodeIndex >= 0 && downNodeIndex < positionsOfVisibleEdges.size() : "upNodeIndex or downNodeIndex has wrong value"; return Tuple.of(new GraphEdge(upNodeIndex, downNodeIndex), pos); }); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/CommitItem.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/CommitItem.java
package com.virtuslab.gitmachete.frontend.graph.impl.items; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.ui.UIUtil; import lombok.Getter; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch; import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.items.ICommitItem; @Getter public final class CommitItem extends BaseGraphItem implements ICommitItem { private final ICommitOfManagedBranch commit; private final INonRootManagedBranchSnapshot containingBranch; public CommitItem( ICommitOfManagedBranch commit, INonRootManagedBranchSnapshot containingBranch, GraphItemColor containingBranchGraphItemColor, @NonNegative int prevSiblingItemIndex, @Positive int nextSiblingItemIndex, @NonNegative int indentLevel) { super(containingBranchGraphItemColor, prevSiblingItemIndex, nextSiblingItemIndex, indentLevel); this.commit = commit; this.containingBranch = containingBranch; } @Override public SimpleTextAttributes getAttributes() { return new SimpleTextAttributes(SimpleTextAttributes.STYLE_ITALIC | SimpleTextAttributes.STYLE_SMALLER, UIUtil.getInactiveTextColor()); } @Override public String getValue() { return commit.getShortMessage(); } @Override public boolean hasBulletPoint() { return false; } @Override public boolean hasChildItem() { return false; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/BranchItem.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/BranchItem.java
package com.virtuslab.gitmachete.frontend.graph.impl.items; import java.awt.Color; import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import lombok.AccessLevel; import lombok.Getter; import org.checkerframework.checker.index.qual.GTENegativeOne; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot; import com.virtuslab.gitmachete.backend.api.RelationToRemote; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.items.IBranchItem; @Getter public final class BranchItem extends BaseGraphItem implements IBranchItem { private final IManagedBranchSnapshot branch; private final RelationToRemote relationToRemote; private final SimpleTextAttributes attributes; private final boolean isCurrentBranch; @Getter(AccessLevel.NONE) private final boolean hasChildItem; public BranchItem( IManagedBranchSnapshot branch, GraphItemColor graphItemColor, RelationToRemote relationToRemote, @GTENegativeOne int prevSiblingItemIndex, @NonNegative int indentLevel, boolean isCurrentBranch, boolean hasChildItem) { super(graphItemColor, prevSiblingItemIndex, indentLevel); this.branch = branch; this.relationToRemote = relationToRemote; this.attributes = isCurrentBranch ? UNDERLINE_BOLD_ATTRIBUTES : NORMAL_ATTRIBUTES; this.isCurrentBranch = isCurrentBranch; this.hasChildItem = hasChildItem; } private static final JBColor BRANCH_TEXT_COLOR = new JBColor(Color.BLACK, Color.WHITE); private static final SimpleTextAttributes UNDERLINE_BOLD_ATTRIBUTES = new SimpleTextAttributes( SimpleTextAttributes.STYLE_UNDERLINE | SimpleTextAttributes.STYLE_BOLD, BRANCH_TEXT_COLOR); private static final SimpleTextAttributes NORMAL_ATTRIBUTES = new SimpleTextAttributes( SimpleTextAttributes.STYLE_PLAIN, BRANCH_TEXT_COLOR); @Override public String getValue() { return branch.getName(); } @Override public boolean hasBulletPoint() { return true; } @Override public boolean hasChildItem() { return hasChildItem; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/BaseGraphItem.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/items/BaseGraphItem.java
package com.virtuslab.gitmachete.frontend.graph.impl.items; import lombok.Getter; import lombok.ToString; import org.checkerframework.checker.index.qual.GTENegativeOne; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; import org.checkerframework.checker.interning.qual.UsesObjectEquals; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; @Getter @ToString @UsesObjectEquals public abstract class BaseGraphItem implements IGraphItem { private final GraphItemColor color; private final @GTENegativeOne int prevSiblingItemIndex; private @MonotonicNonNull @Positive Integer nextSiblingItemIndex = null; private final @NonNegative int indentLevel; protected BaseGraphItem( GraphItemColor color, @GTENegativeOne int prevSiblingItemIndex, @Positive int nextSiblingItemIndex, @NonNegative int indentLevel) { this.color = color; this.prevSiblingItemIndex = prevSiblingItemIndex; this.nextSiblingItemIndex = nextSiblingItemIndex; this.indentLevel = indentLevel; } protected BaseGraphItem( GraphItemColor color, @GTENegativeOne int prevSiblingItemIndex, @NonNegative int indentLevel) { this.color = color; this.prevSiblingItemIndex = prevSiblingItemIndex; this.indentLevel = indentLevel; } @Override public @Nullable @Positive Integer getNextSiblingItemIndex() { return this.nextSiblingItemIndex; } @Override public void setNextSiblingItemIndex(@Positive int i) { assert nextSiblingItemIndex == null : "nextSiblingItemIndex has already been set"; nextSiblingItemIndex = i; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/RenderPartGenerator.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/RenderPartGenerator.java
package com.virtuslab.gitmachete.frontend.graph.impl.render; import com.intellij.util.SmartList; import io.vavr.collection.List; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.initialization.qual.NotOnlyInitialized; import org.checkerframework.checker.initialization.qual.UnderInitialization; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphNode; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; import com.virtuslab.gitmachete.frontend.graph.api.render.IRenderPartGenerator; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IEdgeRenderPart; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph; import com.virtuslab.gitmachete.frontend.graph.impl.render.parts.BaseRenderPart; import com.virtuslab.gitmachete.frontend.graph.impl.render.parts.EdgeRenderPart; import com.virtuslab.gitmachete.frontend.graph.impl.render.parts.NodeRenderPart; public final class RenderPartGenerator implements IRenderPartGenerator { @NotOnlyInitialized private final IRepositoryGraph repositoryGraph; @NotOnlyInitialized private final GraphItemColorForGraphElementProvider itemColorForElementProvider; public RenderPartGenerator(@UnderInitialization IRepositoryGraph repositoryGraph) { this.repositoryGraph = repositoryGraph; this.itemColorForElementProvider = new GraphItemColorForGraphElementProvider(repositoryGraph); } @Override public List<BaseRenderPart> getRenderParts(@NonNegative int rowIndex) { RenderPartBuilder builder = new RenderPartBuilder(rowIndex, itemColorForElementProvider); collectParts(rowIndex, builder); return builder.build(); } private void collectParts(@NonNegative int rowIndex, RenderPartBuilder builder) { IGraphItem graphItem = repositoryGraph.getGraphItem(rowIndex); int position = graphItem.getIndentLevel(); repositoryGraph.getVisibleEdgesWithPositions(rowIndex).forEach(edgeAndPos -> { builder.consumeUpEdge(edgeAndPos._1(), edgeAndPos._2()); builder.consumeDownEdge(edgeAndPos._1(), edgeAndPos._2()); }); List<GraphEdge> adjacentEdges = repositoryGraph.getAdjacentEdges(rowIndex); for (GraphEdge edge : adjacentEdges) { int downNodeIndex = edge.getDownNodeIndex(); int upNodeIndex = edge.getUpNodeIndex(); if (downNodeIndex == rowIndex) { builder.consumeUpEdge(edge, position); } if (upNodeIndex == rowIndex) { builder.consumeDownEdge(edge, position); } } int nodeAndItsDownEdgePos = position; if (graphItem.isBranchItem() && graphItem.asBranchItem().getBranch().isNonRoot()) { builder.consumeRightEdge(new GraphEdge(rowIndex, rowIndex), position); nodeAndItsDownEdgePos++; } builder.consumeNode(new GraphNode(rowIndex), nodeAndItsDownEdgePos); if (graphItem.hasChildItem()) { builder.consumeDownEdge(new GraphEdge(rowIndex, rowIndex + 1), nodeAndItsDownEdgePos); } } @RequiredArgsConstructor private static final class RenderPartBuilder { private final java.util.List<BaseRenderPart> edges = new SmartList<>(); private final java.util.List<BaseRenderPart> nodes = new SmartList<>(); private final @NonNegative int rowIndex; private final GraphItemColorForGraphElementProvider itemColorForElementProvider; void consumeNode(GraphNode node, @NonNegative int position) { nodes.add(new NodeRenderPart(rowIndex, position, node, itemColorForElementProvider)); } void consumeDownEdge(GraphEdge edge, @NonNegative int position) { edges.add(new EdgeRenderPart(rowIndex, position, IEdgeRenderPart.Type.DOWN, edge, itemColorForElementProvider)); } void consumeUpEdge(GraphEdge edge, @NonNegative int position) { edges.add(new EdgeRenderPart(rowIndex, position, IEdgeRenderPart.Type.UP, edge, itemColorForElementProvider)); } void consumeRightEdge(GraphEdge edge, @NonNegative int position) { edges.add(new EdgeRenderPart(rowIndex, position, IEdgeRenderPart.Type.RIGHT, edge, itemColorForElementProvider)); } List<BaseRenderPart> build() { return List.ofAll(edges).appendAll(nodes); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/GraphItemColorForGraphElementProvider.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/GraphItemColorForGraphElementProvider.java
package com.virtuslab.gitmachete.frontend.graph.impl.render; import org.checkerframework.checker.initialization.qual.NotOnlyInitialized; import org.checkerframework.checker.initialization.qual.UnderInitialization; import com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph; public class GraphItemColorForGraphElementProvider { @NotOnlyInitialized private final IRepositoryGraph repositoryGraph; public GraphItemColorForGraphElementProvider(@UnderInitialization IRepositoryGraph repositoryGraph) { this.repositoryGraph = repositoryGraph; } public GraphItemColor getGraphItemColor(IGraphElement element) { int nodeIndex; if (element.isNode()) { nodeIndex = element.asNode().getNodeIndex(); } else { // isEdge nodeIndex = element.asEdge().getDownNodeIndex(); } return repositoryGraph.getGraphItem(nodeIndex).getColor(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/EdgeRenderPart.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/EdgeRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.impl.render.parts; import io.vavr.NotImplementedError; import lombok.Getter; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IEdgeRenderPart; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.INodeRenderPart; import com.virtuslab.gitmachete.frontend.graph.impl.render.GraphItemColorForGraphElementProvider; @Getter public final class EdgeRenderPart extends BaseRenderPart implements IEdgeRenderPart { private final Type type; public EdgeRenderPart( @NonNegative int rowIndex, @NonNegative int positionInRow, Type type, GraphEdge graphEdge, GraphItemColorForGraphElementProvider renderPartColorIdProvider) { super(rowIndex, positionInRow, graphEdge, renderPartColorIdProvider); this.type = type; } @Override public boolean isNode() { return false; } @Override public INodeRenderPart asNode() { throw new NotImplementedError(); } @Override public IEdgeRenderPart asEdge() { return 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/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/BaseRenderPart.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/BaseRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.impl.render.parts; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; import com.virtuslab.gitmachete.frontend.graph.impl.render.GraphItemColorForGraphElementProvider; @RequiredArgsConstructor public abstract class BaseRenderPart implements IRenderPart { @Getter protected final @NonNegative int rowIndex; @Getter protected final @NonNegative int positionInRow; protected final IGraphElement graphElement; private final GraphItemColorForGraphElementProvider renderPartColorIdProvider; @Override public GraphItemColor getGraphItemColor() { return renderPartColorIdProvider.getGraphItemColor(graphElement); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/NodeRenderPart.java
frontend/graph/impl/src/main/java/com/virtuslab/gitmachete/frontend/graph/impl/render/parts/NodeRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.impl.render.parts; import io.vavr.NotImplementedError; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphNode; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IEdgeRenderPart; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.INodeRenderPart; import com.virtuslab.gitmachete.frontend.graph.impl.render.GraphItemColorForGraphElementProvider; public final class NodeRenderPart extends BaseRenderPart implements INodeRenderPart { public NodeRenderPart( @NonNegative int rowIndex, @NonNegative int positionInRow, GraphNode graphNode, GraphItemColorForGraphElementProvider renderPartColorIdProvider) { super(rowIndex, positionInRow, graphNode, renderPartColorIdProvider); } @Override public boolean isNode() { return true; } @Override public INodeRenderPart asNode() { return this; } @Override public IEdgeRenderPart asEdge() { throw new NotImplementedError(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/IGraphCellPainter.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/IGraphCellPainter.java
package com.virtuslab.gitmachete.frontend.graph.api.paint; import java.awt.Graphics2D; import io.vavr.collection.List; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; public interface IGraphCellPainter { @UIEffect void draw(Graphics2D g2, List<? extends IRenderPart> renderParts); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/IGraphCellPainterFactory.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/IGraphCellPainterFactory.java
package com.virtuslab.gitmachete.frontend.graph.api.paint; import javax.swing.JTable; public interface IGraphCellPainterFactory { IGraphCellPainter create(JTable table); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/PaintParameters.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/paint/PaintParameters.java
package com.virtuslab.gitmachete.frontend.graph.api.paint; public final class PaintParameters { private PaintParameters() {} private static final int CIRCLE_RADIUS = 4; private static final float THICK_LINE = 1.5f; private static final int WIDTH_NODE = 15; public static final int ROW_HEIGHT = 22; public static int getNodeWidth(int rowHeight) { return WIDTH_NODE * rowHeight / ROW_HEIGHT; } public static float getLineThickness(int rowHeight) { return THICK_LINE * rowHeight / ROW_HEIGHT; } public static int getCircleRadius(int rowHeight) { return CIRCLE_RADIUS * rowHeight / ROW_HEIGHT; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/IGraphElement.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/IGraphElement.java
package com.virtuslab.gitmachete.frontend.graph.api.elements; import org.checkerframework.framework.qual.EnsuresQualifierIf; import org.checkerframework.framework.qual.RequiresQualifier; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements.ConfirmedGraphEdge; import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements.ConfirmedGraphNode; /** * Graph elements ({@link IGraphElement}, {@link GraphEdge}, {@link GraphNode}) represent the LOGICAL graph structure. * In this scope there are only graph nodes and edges connecting them. * The actual position of elements (in graph table or relative to each other) does not count * here (unlike with {@link IRenderPart}). * */ public interface IGraphElement { @EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedGraphNode.class) @EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedGraphEdge.class) boolean isNode(); @EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedGraphEdge.class) @EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedGraphNode.class) default boolean isEdge() { return !isNode(); } @RequiresQualifier(expression = "this", qualifier = ConfirmedGraphNode.class) GraphNode asNode(); @RequiresQualifier(expression = "this", qualifier = ConfirmedGraphEdge.class) GraphEdge asEdge(); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/GraphEdge.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/GraphEdge.java
package com.virtuslab.gitmachete.frontend.graph.api.elements; import io.vavr.NotImplementedError; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.index.qual.NonNegative; @Getter @RequiredArgsConstructor public final class GraphEdge implements IGraphElement { public static GraphEdge createEdge(@NonNegative int nodeIndex1, @NonNegative int nodeIndex2) { return new GraphEdge(Math.min(nodeIndex1, nodeIndex2), Math.max(nodeIndex1, nodeIndex2)); } private final @NonNegative int upNodeIndex; private final @NonNegative int downNodeIndex; @Override public boolean isNode() { return false; } @Override public GraphNode asNode() { throw new NotImplementedError(); } @Override public GraphEdge asEdge() { return 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/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/GraphNode.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/elements/GraphNode.java
package com.virtuslab.gitmachete.frontend.graph.api.elements; import io.vavr.NotImplementedError; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.index.qual.NonNegative; @RequiredArgsConstructor public final class GraphNode implements IGraphElement { @Getter private final @NonNegative int nodeIndex; @Override public boolean isNode() { return true; } @Override public GraphNode asNode() { return this; } @Override public GraphEdge asEdge() { throw new NotImplementedError(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IRepositoryGraphCache.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IRepositoryGraphCache.java
package com.virtuslab.gitmachete.frontend.graph.api.repository; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot; public interface IRepositoryGraphCache { @UIEffect IRepositoryGraph getRepositoryGraph(IGitMacheteRepositorySnapshot givenRepositorySnapshot, boolean isListingCommits); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IRepositoryGraph.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IRepositoryGraph.java
package com.virtuslab.gitmachete.frontend.graph.api.repository; import io.vavr.Tuple2; import io.vavr.collection.List; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; public interface IRepositoryGraph { List<GraphEdge> getAdjacentEdges(@NonNegative int itemIndex); IGraphItem getGraphItem(@NonNegative int itemIndex); @NonNegative int getNodesCount(); List<? extends IRenderPart> getRenderParts(@NonNegative int itemIndex); List<Tuple2<GraphEdge, @NonNegative Integer>> getVisibleEdgesWithPositions(@NonNegative int itemIndex); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/NullRepositoryGraph.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/NullRepositoryGraph.java
package com.virtuslab.gitmachete.frontend.graph.api.repository; import io.vavr.NotImplementedError; import io.vavr.Tuple2; import io.vavr.collection.List; import lombok.Getter; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge; import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; public final class NullRepositoryGraph implements IRepositoryGraph { @Getter private static final NullRepositoryGraph instance = new NullRepositoryGraph(); private NullRepositoryGraph() {} @Override public List<GraphEdge> getAdjacentEdges(@NonNegative int itemIndex) { return List.empty(); } @Override public IGraphItem getGraphItem(@NonNegative int itemIndex) { throw new NotImplementedError(); } @Override public @NonNegative int getNodesCount() { return 0; } @Override public List<? extends IRenderPart> getRenderParts(@NonNegative int itemIndex) { return List.empty(); } @Override public List<Tuple2<GraphEdge, @NonNegative Integer>> getVisibleEdgesWithPositions(@NonNegative int itemIndex) { return List.empty(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IBranchGetCommitsStrategy.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/repository/IBranchGetCommitsStrategy.java
package com.virtuslab.gitmachete.frontend.graph.api.repository; import io.vavr.collection.List; import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch; import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot; public interface IBranchGetCommitsStrategy { List<ICommitOfManagedBranch> getCommitsOf(INonRootManagedBranchSnapshot branch); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/ICommitItem.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/ICommitItem.java
package com.virtuslab.gitmachete.frontend.graph.api.items; import io.vavr.NotImplementedError; import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch; import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot; public interface ICommitItem extends IGraphItem { // These methods need to be implemented in frontendGraphApi (as opposed to an implementation subproject) // to avoid problems with Subtyping Checker. @Override default boolean isBranchItem() { return false; } @Override default IBranchItem asBranchItem() { throw new NotImplementedError(); } @Override default ICommitItem asCommitItem() { return this; } ICommitOfManagedBranch getCommit(); /** * @return a non-root branch containing the given commit in git-machete sense, which is stricter than containing in git sense. * * <p><b>Branch A "contains" commit X in git sense</b> means that * there's a path (possibly of zero length) from the commit pointed by A to commit X.</p> * * <p><b>Branch A "contains" commit X in git-machete sense</b> means that * A is a non-root branch and X lies between commit pointed by A and A's fork point.</p> */ INonRootManagedBranchSnapshot getContainingBranch(); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/IGraphItem.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/IGraphItem.java
package com.virtuslab.gitmachete.frontend.graph.api.items; import com.intellij.ui.SimpleTextAttributes; import org.checkerframework.checker.index.qual.GTENegativeOne; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.EnsuresQualifierIf; import org.checkerframework.framework.qual.RequiresQualifier; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items.ConfirmedBranchItem; import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items.ConfirmedCommitItem; /** * Graph items ({@link IGraphItem}, {@link IBranchItem}, {@link ICommitItem}) represent the DATA of the graph. * There is no strict concept of edge here (unlike {@link com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement} * and {@link IRenderPart}). * Items relation is defined by indices of cells in the graph table. * */ public interface IGraphItem { /** * @return the index of previous sibling item (above in table) that is connected directly * and thus at the same indent level in graph as this one. */ @GTENegativeOne int getPrevSiblingItemIndex(); /** * @return the index of next sibling item (below in table) that is connected directly * and thus at the same indent level in graph as this one (hence it is not its child item). * <ul> * <li>for a commit item, it's either another commit item or the containing branch (never null),</li> * <li>for a branch item, it's either next sibling branch item or null (if none left)</li> * </ul> */ @Nullable @Positive Integer getNextSiblingItemIndex(); void setNextSiblingItemIndex(@Positive int i); /** @return the text (commit message/branch name) to be displayed in the table */ String getValue(); /** @return the attributes (eg. boldness) to be used by the displayed text */ SimpleTextAttributes getAttributes(); GraphItemColor getColor(); @NonNegative int getIndentLevel(); boolean hasBulletPoint(); /** @return the childItem which is an indented item (branch or commit) */ boolean hasChildItem(); @EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedBranchItem.class) @EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedCommitItem.class) boolean isBranchItem(); @EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedCommitItem.class) @EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedBranchItem.class) default boolean isCommitItem() { return !isBranchItem(); } @RequiresQualifier(expression = "this", qualifier = ConfirmedBranchItem.class) IBranchItem asBranchItem(); @RequiresQualifier(expression = "this", qualifier = ConfirmedCommitItem.class) ICommitItem asCommitItem(); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/IBranchItem.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/IBranchItem.java
package com.virtuslab.gitmachete.frontend.graph.api.items; import io.vavr.NotImplementedError; import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot; import com.virtuslab.gitmachete.backend.api.RelationToRemote; public interface IBranchItem extends IGraphItem { IManagedBranchSnapshot getBranch(); RelationToRemote getRelationToRemote(); boolean isCurrentBranch(); // These methods need to be implemented in frontendGraphApi to avoid problems with Subtyping Checker. @Override default boolean isBranchItem() { return true; } @Override default IBranchItem asBranchItem() { return this; } @Override default ICommitItem asCommitItem() { throw new NotImplementedError(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/GraphItemColor.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/items/GraphItemColor.java
package com.virtuslab.gitmachete.frontend.graph.api.items; public enum GraphItemColor { TRANSPARENT, GRAY, YELLOW, RED, GREEN }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/IRenderPartGenerator.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/IRenderPartGenerator.java
package com.virtuslab.gitmachete.frontend.graph.api.render; import io.vavr.collection.List; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart; public interface IRenderPartGenerator { List<? extends IRenderPart> getRenderParts(@NonNegative int rowIndex); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/INodeRenderPart.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/INodeRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.api.render.parts; public interface INodeRenderPart extends IRenderPart {}
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/IRenderPart.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/IRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.api.render.parts; import org.checkerframework.checker.index.qual.NonNegative; import com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement; import com.virtuslab.gitmachete.frontend.graph.api.items.GraphItemColor; /** * Render parts ({@link IRenderPart}, {@link IEdgeRenderPart}, {@link INodeRenderPart}) represent RENDERED graph. * The position of unit parts (row of and position within graph table), orientation of edges are important here. * In this context the connections between graph elements does not matter (unlike {@link IGraphElement}s). * */ public interface IRenderPart { @NonNegative int getRowIndex(); @NonNegative int getPositionInRow(); GraphItemColor getGraphItemColor(); boolean isNode(); INodeRenderPart asNode(); IEdgeRenderPart asEdge(); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/IEdgeRenderPart.java
frontend/graph/api/src/main/java/com/virtuslab/gitmachete/frontend/graph/api/render/parts/IEdgeRenderPart.java
package com.virtuslab.gitmachete.frontend.graph.api.render.parts; public interface IEdgeRenderPart extends IRenderPart { Type getType(); enum Type { UP, DOWN, RIGHT } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/ResetCurrentToRemoteBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/ResetCurrentToRemoteBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.actions.base.BaseResetToRemoteAction.VCS_NOTIFIER_TITLE; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import static git4idea.GitNotificationIdsHolder.LOCAL_CHANGES_DETECTED; import static git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector.Operation.RESET; import com.intellij.dvcs.DvcsUtil; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vfs.VfsUtil; import git4idea.commands.Git; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; import git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.util.LocalChangesWouldBeOverwrittenHelper; import lombok.CustomLog; import lombok.experimental.ExtensionMethod; import lombok.val; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @CustomLog @ExtensionMethod({GitMacheteBundle.class}) // For some reason, using `@ExtensionMethod({GitVfsUtils.class})` on this class // leads to weird Checker Framework errors :/ public class ResetCurrentToRemoteBackgroundable extends SideEffectingBackgroundable { private final String localBranchName; private final String remoteTrackingBranchName; private final GitRepository gitRepository; public ResetCurrentToRemoteBackgroundable(String localBranchName, String remoteTrackingBranchName, GitRepository gitRepository) { super(gitRepository.getProject(), getNonHtmlString("action.GitMachete.ResetCurrentToRemoteBackgroundable.task-title"), "reset"); this.localBranchName = localBranchName; this.remoteTrackingBranchName = remoteTrackingBranchName; this.gitRepository = gitRepository; } @Override @UIThreadUnsafe public void doRun(ProgressIndicator indicator) { if (localBranchName != null && remoteTrackingBranchName != null) { LOG.debug(() -> "Resetting '${localBranchName}' to '${remoteTrackingBranchName}'"); try (AccessToken ignored = DvcsUtil.workingTreeChangeStarted(project, getString("action.GitMachete.ResetCurrentToRemoteBackgroundable.task-title"))) { val resetHandler = new GitLineHandler(project, gitRepository.getRoot(), GitCommand.RESET); resetHandler.addParameters("--keep"); resetHandler.addParameters(remoteTrackingBranchName); resetHandler.endOptions(); val localChangesDetector = new GitLocalChangesWouldBeOverwrittenDetector(gitRepository.getRoot(), RESET); resetHandler.addLineListener(localChangesDetector); val result = Git.getInstance().runCommand(resetHandler); if (result.success()) { VcsNotifier.getInstance(project).notifySuccess( /* displayId */ null, /* title */ "", getString("action.GitMachete.BaseResetToRemoteAction.notification.title.reset-success.HTML") .fmt(localBranchName)); LOG.debug(() -> "Branch '${localBranchName}' has been reset to '${remoteTrackingBranchName}"); } else if (localChangesDetector.wasMessageDetected()) { LocalChangesWouldBeOverwrittenHelper.showErrorNotification(project, LOCAL_CHANGES_DETECTED, gitRepository.getRoot(), /* operationName */ "Reset", localChangesDetector.getRelativeFilePaths()); } else { LOG.error(result.getErrorOutputAsJoinedString()); VcsNotifier.getInstance(project).notifyError(/* displayId */ null, VCS_NOTIFIER_TITLE, result.getErrorOutputAsHtmlString()); } val repositoryRoot = gitRepository.getRoot(); GitRepositoryManager.getInstance(project).updateRepository(repositoryRoot); VfsUtil.markDirtyAndRefresh(/* async */ false, /* recursive */ true, /* reloadChildren */ false, repositoryRoot); } } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SideEffectingBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SideEffectingBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import lombok.val; import org.checkerframework.checker.tainting.qual.Untainted; import com.virtuslab.gitmachete.frontend.actions.common.SideEffectingActionTrackingService; import com.virtuslab.qual.guieffect.UIThreadUnsafe; public abstract class SideEffectingBackgroundable extends Task.Backgroundable { // Task.Backgroundable already brings in a protected `myProject`, but it's @Nullable, // which forces unnecessary null checks to satisfy static analysis. protected final Project project; private final @Untainted String shortName; public SideEffectingBackgroundable(Project project, @Untainted String title, @Untainted String shortName) { super(project, title); this.project = project; this.shortName = shortName; } @Override @UIThreadUnsafe public final void run(ProgressIndicator indicator) { try (val ignored = project.getService(SideEffectingActionTrackingService.class).register(shortName)) { doRun(indicator); } } @UIThreadUnsafe protected abstract void doRun(ProgressIndicator indicator); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/OverrideForkPointBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/OverrideForkPointBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.defs.GitConfigKeys.overrideForkPointToKey; import static com.virtuslab.gitmachete.frontend.defs.GitConfigKeys.overrideForkPointWhileDescendantOf; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import git4idea.config.GitConfigUtil; import git4idea.repo.GitRepository; import lombok.CustomLog; import lombok.val; 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.INonRootManagedBranchSnapshot; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.qual.async.ContinuesInBackground; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @CustomLog public class OverrideForkPointBackgroundable extends SideEffectingBackgroundable { private final GitRepository gitRepository; private final INonRootManagedBranchSnapshot nonRootBranch; @Nullable private final ICommitOfManagedBranch selectedCommit; private final BaseEnhancedGraphTable graphTable; public OverrideForkPointBackgroundable(GitRepository gitRepository, INonRootManagedBranchSnapshot nonRootBranch, BaseEnhancedGraphTable graphTable, @Nullable ICommitOfManagedBranch selectedCommit) { super(gitRepository.getProject(), getNonHtmlString("action.GitMachete.OverrideForkPointBackgroundable.task.title"), "fork point override"); this.gitRepository = gitRepository; this.nonRootBranch = nonRootBranch; this.graphTable = graphTable; this.selectedCommit = selectedCommit; } @Override @ContinuesInBackground @UIThreadUnsafe public void doRun(ProgressIndicator indicator) { if (selectedCommit != null) { LOG.debug("Enqueueing fork point override"); overrideForkPoint(nonRootBranch, selectedCommit); } else { LOG.debug("Commit selected to be the new fork point is null: " + "most likely the action has been canceled from override-fork-point dialog"); } } @ContinuesInBackground @UIThreadUnsafe private void overrideForkPoint(IManagedBranchSnapshot branch, ICommitOfManagedBranch forkPoint) { if (gitRepository != null) { val root = gitRepository.getRoot(); setOverrideForkPointConfigValues(project, root, branch.getName(), forkPoint); } // required since the change of .git/config is not considered as a change to VCS (and detected by the listener) graphTable.queueRepositoryUpdateAndModelRefresh(); } @UIThreadUnsafe private void setOverrideForkPointConfigValues( Project project, VirtualFile root, String branchName, ICommitOfManagedBranch forkPoint) { val toKey = overrideForkPointToKey(branchName); val whileDescendantOfKey = overrideForkPointWhileDescendantOf(branchName); try { GitConfigUtil.setValue(project, root, toKey, forkPoint.getHash()); } catch (VcsException e) { LOG.info("Attempt to set '${toKey}' git config value failed: " + e.getMessage()); } try { // As a step towards deprecation of `whileDescendantOf` key (see #1580), // let's just set its value to the same as `to` key. // This will mitigate the problem pointed out in https://github.com/VirtusLab/git-machete/issues/611, // while not breaking older git-machete clients (esp. CLI) that still require `whileDescendantOf` key to be present // for a fork point override to be valid. GitConfigUtil.setValue(project, root, whileDescendantOfKey, forkPoint.getHash()); } catch (VcsException e) { LOG.info("Attempt to get '${whileDescendantOfKey}' git config value failed: " + e.getMessage()); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/FetchBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/FetchBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsNotifier; import git4idea.GitUtil; import git4idea.fetch.GitFetchSupport; import git4idea.repo.GitRemote; import git4idea.repo.GitRepository; import lombok.CustomLog; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.tainting.qual.Untainted; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @CustomLog public class FetchBackgroundable extends SideEffectingBackgroundable { private final GitRepository gitRepository; private final String remoteName; private final @Nullable String refspec; private final @Untainted String failureNotificationText; private final String successNotificationText; /** Use as {@code remoteName} when referring to the local repository. */ public static final String LOCAL_REPOSITORY_NAME = "."; public FetchBackgroundable( GitRepository gitRepository, String remoteName, @Nullable String refspec, @Untainted String taskTitle, @Untainted String failureNotificationText, String successNotificationText) { super(gitRepository.getProject(), taskTitle, "fetch"); this.gitRepository = gitRepository; this.remoteName = remoteName; this.refspec = refspec; this.failureNotificationText = failureNotificationText; this.successNotificationText = successNotificationText; } @Override @UIThreadUnsafe public void doRun(ProgressIndicator indicator) { val fetchSupport = GitFetchSupport.fetchSupport(gitRepository.getProject()); GitRemote remote = remoteName.equals(LOCAL_REPOSITORY_NAME) ? GitRemote.DOT : GitUtil.findRemoteByName(gitRepository, remoteName); if (remote == null) { // This is generally NOT expected, the task should never be triggered // for an invalid remote in the first place. LOG.warn("Remote '${remoteName}' does not exist"); return; } val fetchResult = refspec != null ? fetchSupport.fetch(gitRepository, remote, refspec) : fetchSupport.fetch(gitRepository, remote); fetchResult.showNotificationIfFailed(failureNotificationText); fetchResult.throwExceptionIfFailed(); } @UIEffect @Override public void onSuccess() { VcsNotifier.getInstance(gitRepository.getProject()).notifySuccess(/* displayId */ null, /* title */ "", successNotificationText); } @Override public void onThrowable(Throwable error) { // ignore - notification already shown from `run` implementation } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/GitCommandUpdatingCurrentBranchBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/GitCommandUpdatingCurrentBranchBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.intellij.notification.NotificationType.INFORMATION; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import static git4idea.GitNotificationIdsHolder.LOCAL_CHANGES_DETECTED; import static git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector.Operation.MERGE; import static git4idea.update.GitUpdateSessionKt.getBodyForUpdateNotification; import static git4idea.update.GitUpdateSessionKt.getTitleForUpdateNotification; import com.intellij.dvcs.DvcsUtil; import com.intellij.history.Label; import com.intellij.history.LocalHistory; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction; import com.intellij.openapi.vcs.update.ActionInfo; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.util.ModalityUiUtil; import com.intellij.vcs.ViewUpdateInfoNotification; import git4idea.GitBranch; import git4idea.GitRevisionNumber; import git4idea.GitVcs; import git4idea.branch.GitBranchPair; import git4idea.commands.Git; import git4idea.commands.GitCommandResult; import git4idea.commands.GitLineHandler; import git4idea.commands.GitLocalChangesWouldBeOverwrittenDetector; import git4idea.commands.GitUntrackedFilesOverwrittenByOperationDetector; import git4idea.merge.MergeChangeCollector; import git4idea.repo.GitRepository; import git4idea.update.GitUpdateInfoAsLog; import git4idea.update.GitUpdatedRanges; import git4idea.util.GitUntrackedFilesHelper; import git4idea.util.LocalChangesWouldBeOverwrittenHelper; import kr.pe.kwonnam.slf4jlambda.LambdaLogger; import lombok.val; import org.checkerframework.checker.guieffect.qual.UI; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.i18nformatter.qual.I18nFormat; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.tainting.qual.Untainted; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.qual.guieffect.UIThreadUnsafe; public abstract class GitCommandUpdatingCurrentBranchBackgroundable extends SideEffectingBackgroundable { protected final GitRepository gitRepository; public GitCommandUpdatingCurrentBranchBackgroundable( GitRepository gitRepository, @Untainted String taskTitle, @Untainted String shortName) { super(gitRepository.getProject(), taskTitle, shortName); this.gitRepository = gitRepository; } protected abstract LambdaLogger log(); protected abstract @Untainted @I18nFormat({}) String getOperationName(); protected abstract String getTargetBranchName(); @UIThreadUnsafe protected abstract @Nullable GitLineHandler createGitLineHandler(); @Override @UIThreadUnsafe public final void doRun(ProgressIndicator indicator) { val handler = createGitLineHandler(); if (handler == null) { return; } val localChangesDetector = new GitLocalChangesWouldBeOverwrittenDetector( gitRepository.getRoot(), MERGE); val untrackedFilesDetector = new GitUntrackedFilesOverwrittenByOperationDetector( gitRepository.getRoot()); handler.addLineListener(localChangesDetector); handler.addLineListener(untrackedFilesDetector); Label beforeLabel = LocalHistory.getInstance().putSystemLabel(project, /* name */ "Before update"); GitUpdatedRanges updatedRanges = deriveGitUpdatedRanges(getTargetBranchName()); String beforeRevision = gitRepository.getCurrentRevision(); try (AccessToken ignore = DvcsUtil.workingTreeChangeStarted(project, getOperationName())) { GitCommandResult result = Git.getInstance().runCommand(handler); if (beforeRevision != null) { GitRevisionNumber currentRev = new GitRevisionNumber(beforeRevision); handleResult(result, localChangesDetector, untrackedFilesDetector, currentRev, beforeLabel, updatedRanges); } } } @UIThreadUnsafe private @Nullable GitUpdatedRanges deriveGitUpdatedRanges(String targetBranchName) { GitUpdatedRanges updatedRanges = null; val currentBranch = gitRepository.getCurrentBranch(); if (currentBranch != null) { GitBranch targetBranch = gitRepository.getBranches().findBranchByName(targetBranchName); if (targetBranch != null) { GitBranchPair refPair = new GitBranchPair(currentBranch, targetBranch); updatedRanges = GitUpdatedRanges.calcInitialPositions(project, java.util.Collections.singletonMap(gitRepository, refPair)); } else { log().warn("Couldn't find the branch with name '${targetBranchName}'"); } } return updatedRanges; } @UIThreadUnsafe private void handleResult( GitCommandResult result, GitLocalChangesWouldBeOverwrittenDetector localChangesDetector, GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector, GitRevisionNumber currentRev, Label beforeLabel, @Nullable GitUpdatedRanges updatedRanges) { val root = gitRepository.getRoot(); if (result.success()) { VfsUtil.markDirtyAndRefresh(/* async */ false, /* recursive */ true, /* reloadChildren */ false, root); gitRepository.update(); if (updatedRanges != null && AbstractCommonUpdateAction .showsCustomNotification(java.util.Collections.singletonList(GitVcs.getInstance(project)))) { val ranges = updatedRanges.calcCurrentPositions(); GitUpdateInfoAsLog.NotificationData notificationData = new GitUpdateInfoAsLog(project, ranges) .calculateDataAndCreateLogTab(); Notification notification; if (notificationData != null) { val title = getTitleForUpdateNotification(notificationData.getUpdatedFilesCount(), notificationData.getReceivedCommitsCount()); val content = getBodyForUpdateNotification(notificationData.getFilteredCommitsCount()); notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(title, content, INFORMATION); notification.addAction(NotificationAction.createSimple(getString( "action.GitMachete.GitCommandUpdatingCurrentBranchBackgroundable.notification.message.view-commits"), notificationData.getViewCommitAction())); } else { // When the pull results with no commits, there is no git update info (as log). // Based on that we know that all files are up-to-date. notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification( getString( "action.GitMachete.GitCommandUpdatingCurrentBranchBackgroundable.notification.title.all-files-are-up-to-date"), /* content */ "", INFORMATION); } VcsNotifier.getInstance(project).notify(notification); } else { showUpdates(currentRev, beforeLabel); } } else if (localChangesDetector.wasMessageDetected()) { LocalChangesWouldBeOverwrittenHelper.showErrorNotification(project, LOCAL_CHANGES_DETECTED, gitRepository.getRoot(), getOperationName(), localChangesDetector.getRelativeFilePaths()); } else if (untrackedFilesDetector.wasMessageDetected()) { GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, root, untrackedFilesDetector.getRelativeFilePaths(), getOperationName(), /* description */ null); } else { VcsNotifier.getInstance(project).notifyError( /* displayId */ null, GitMacheteBundle.fmt( getString("action.GitMachete.GitCommandUpdatingCurrentBranchBackgroundable.notification.title.update-fail"), getOperationName()), result.getErrorOutputAsJoinedString()); gitRepository.update(); } } @UIThreadUnsafe private void showUpdates(GitRevisionNumber currentRev, Label beforeLabel) { String operationName = GitCommandUpdatingCurrentBranchBackgroundable.this.getOperationName(); try { UpdatedFiles files = UpdatedFiles.create(); val collector = new MergeChangeCollector(project, gitRepository, currentRev); collector.collect(files); ModalityUiUtil.invokeLaterIfNeeded(ModalityState.defaultModalityState(), new @UI Runnable() { @Override @UIEffect public void run() { val manager = ProjectLevelVcsManagerEx.getInstanceEx(project); val tree = manager.showUpdateProjectInfo(files, operationName, ActionInfo.UPDATE, /* canceled */ false); if (tree != null) { tree.setBefore(beforeLabel); tree.setAfter(LocalHistory.getInstance().putSystemLabel(project, /* name */ "After update")); ViewUpdateInfoNotification.focusUpdateInfoTree(project, tree); } } }); } catch (VcsException e) { GitVcs.getInstance(project).showErrors(java.util.Collections.singletonList(e), operationName); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/MergeCurrentBranchFastForwardOnlyBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/MergeCurrentBranchFastForwardOnlyBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; import git4idea.repo.GitRepository; import kr.pe.kwonnam.slf4jlambda.LambdaLogger; import lombok.CustomLog; import lombok.val; import org.checkerframework.checker.i18nformatter.qual.I18nFormat; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.tainting.qual.Untainted; import com.virtuslab.gitmachete.backend.api.IBranchReference; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @CustomLog public class MergeCurrentBranchFastForwardOnlyBackgroundable extends GitCommandUpdatingCurrentBranchBackgroundable { private final IBranchReference targetBranch; @Override public String getTargetBranchName() { return targetBranch.getName(); } public MergeCurrentBranchFastForwardOnlyBackgroundable( GitRepository gitRepository, IBranchReference targetBranch) { super(gitRepository, getNonHtmlString("action.GitMachete.MergeCurrentBranchFastForwardOnlyBackgroundable.task-title"), "fast-forward merge of current branch"); this.targetBranch = targetBranch; } @Override protected LambdaLogger log() { return LOG; } @Override protected @I18nFormat({}) @Untainted String getOperationName() { return getNonHtmlString("action.GitMachete.MergeCurrentBranchFastForwardOnlyBackgroundable.operation-name"); } @Override @UIThreadUnsafe protected @Nullable GitLineHandler createGitLineHandler() { val handler = new GitLineHandler(project, gitRepository.getRoot(), GitCommand.MERGE); handler.addParameters("--ff-only"); handler.addParameters(targetBranch.getFullName()); return handler; } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/BaseSlideInBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/BaseSlideInBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.actions.common.BranchCreationUtils.waitForCreationOfLocalBranch; import static com.virtuslab.gitmachete.frontend.common.WriteActionUtils.blockingRunWriteActionOnUIThread; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import java.nio.file.Path; import java.util.Objects; import com.intellij.openapi.progress.ProgressIndicator; import git4idea.repo.GitRepository; import io.vavr.collection.List; import lombok.experimental.ExtensionMethod; 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.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.gitmachete.frontend.actions.common.SlideInOptions; import com.virtuslab.gitmachete.frontend.actions.common.UiThreadUnsafeRunnable; import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; import com.virtuslab.qual.async.ContinuesInBackground; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class, Objects.class}) public abstract class BaseSlideInBackgroundable extends SideEffectingBackgroundable { private final GitRepository gitRepository; private final BranchLayout branchLayout; private final IBranchLayoutWriter branchLayoutWriter; private final BaseEnhancedGraphTable graphTable; private final UiThreadUnsafeRunnable preSlideInRunnable; protected final SlideInOptions slideInOptions; public BaseSlideInBackgroundable( GitRepository gitRepository, BranchLayout branchLayout, IBranchLayoutWriter branchLayoutWriter, BaseEnhancedGraphTable graphTable, UiThreadUnsafeRunnable preSlideInRunnable, SlideInOptions slideInOptions) { super(gitRepository.getProject(), getNonHtmlString("action.GitMachete.BaseSlideInBackgroundable.task-title"), "slide-in"); this.gitRepository = gitRepository; this.branchLayout = branchLayout; this.branchLayoutWriter = branchLayoutWriter; this.graphTable = graphTable; this.preSlideInRunnable = preSlideInRunnable; this.slideInOptions = slideInOptions; } @Override @UIThreadUnsafe public final void doRun(ProgressIndicator indicator) { graphTable.disableEnqueuingUpdates(); preSlideInRunnable.run(); // `preSlideInRunnable` may perform some sneakily-asynchronous operations (e.g. checkoutRemoteBranch). // The high-level method used within the runnable does not allow us to schedule the tasks after them. // (Stepping deeper is not an option since we would lose some important logic or become very dependent on the internals of git4idea). // Hence, we wait for the creation of the branch (with exponential backoff). waitForCreationOfLocalBranch(gitRepository, slideInOptions.getName()); Path macheteFilePath = gitRepository.getMacheteFilePath(); val childEntryByName = branchLayout.getEntryByName(slideInOptions.getName()); BranchLayoutEntry entryToSlideIn; BranchLayout targetBranchLayout; if (childEntryByName != null) { if (slideInOptions.shouldReattach()) { entryToSlideIn = childEntryByName.withCustomAnnotation(slideInOptions.getCustomAnnotation()); targetBranchLayout = branchLayout; } else { entryToSlideIn = childEntryByName.withChildren(List.empty()).withCustomAnnotation(slideInOptions.getCustomAnnotation()); targetBranchLayout = branchLayout.slideOut(slideInOptions.getName()); } } else { entryToSlideIn = new BranchLayoutEntry(slideInOptions.getName(), slideInOptions.getCustomAnnotation(), /* children */ List.empty()); targetBranchLayout = branchLayout; } val newBranchLayout = deriveNewBranchLayout(targetBranchLayout, entryToSlideIn); if (newBranchLayout == null) { return; } blockingRunWriteActionOnUIThread(() -> { MacheteFileWriter.writeBranchLayout( macheteFilePath, branchLayoutWriter, newBranchLayout, /* backupOldLayout */ true, /* requestor */ this); }); } @Override @ContinuesInBackground public final void onFinished() { graphTable.enableEnqueuingUpdates(); } abstract @Nullable BranchLayout deriveNewBranchLayout(BranchLayout targetBranchLayout, BranchLayoutEntry entryToSlideIn); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/RebaseOnParentBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/RebaseOnParentBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.util.Collections; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsNotifier; import git4idea.branch.GitBranchUiHandlerImpl; import git4idea.branch.GitBranchWorker; import git4idea.branch.GitRebaseParams; import git4idea.commands.Git; import git4idea.rebase.GitRebaseUtils; import git4idea.repo.GitRepository; import lombok.CustomLog; import lombok.experimental.ExtensionMethod; import lombok.val; import com.virtuslab.gitmachete.backend.api.GitMacheteMissingForkPointException; import com.virtuslab.gitmachete.backend.api.IGitRebaseParameters; import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot; import com.virtuslab.gitmachete.frontend.actions.hooks.PreRebaseHookExecutor; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod(GitMacheteBundle.class) @CustomLog public class RebaseOnParentBackgroundable extends SideEffectingBackgroundable { private static final String NL = System.lineSeparator(); private final GitRepository gitRepository; private final INonRootManagedBranchSnapshot branchToRebase; private final boolean shouldExplicitlyCheckout; public RebaseOnParentBackgroundable(GitRepository gitRepository, INonRootManagedBranchSnapshot branchToRebase, boolean shouldExplicitlyCheckout) { super(gitRepository.getProject(), getNonHtmlString("action.GitMachete.RebaseOnParentBackgroundable.task-title"), /* shortName */ "rebase"); this.gitRepository = gitRepository; this.branchToRebase = branchToRebase; this.shouldExplicitlyCheckout = shouldExplicitlyCheckout; LOG.debug(() -> "Entering: gitRepository = ${gitRepository}, branchToRebase = ${branchToRebase}"); } @UIThreadUnsafe private GitRebaseParams getIdeaRebaseParamsOf(GitRepository repository, IGitRebaseParameters gitRebaseParams) { val gitVersion = repository.getVcs().getVersion(); val currentBranchName = gitRebaseParams.getCurrentBranch().getName(); val newBaseBranchFullName = gitRebaseParams.getNewBaseBranch().getFullName(); val forkPointCommitHash = gitRebaseParams.getForkPointCommit().getHash(); return new GitRebaseParams(gitVersion, currentBranchName, newBaseBranchFullName, /* upstream */ forkPointCommitHash, /* interactive */ true, /* preserveMerges */ false); } @Override @UIThreadUnsafe public void doRun(ProgressIndicator indicator) { IGitRebaseParameters gitRebaseParameters; try { gitRebaseParameters = branchToRebase.getParametersForRebaseOntoParent(); LOG.debug(() -> "Queuing the machete-pre-rebase hook and the rebase background task for branch " + "'${branchToRebase.getName()}"); } catch (GitMacheteMissingForkPointException e) { val message = e.getMessage() == null ? "Unable to get rebase parameters." : e.getMessage(); LOG.error(message); VcsNotifier.getInstance(project).notifyError(/* displayId */ null, getString("action.GitMachete.RebaseOnParentBackgroundable.notification.title.rebase-fail"), message); return; } val preRebaseHookExecutor = new PreRebaseHookExecutor(gitRepository); if (!preRebaseHookExecutor.executeHookFor(gitRebaseParameters)) { return; } val params = getIdeaRebaseParamsOf(gitRepository, gitRebaseParameters); LOG.info("Rebasing '${gitRebaseParameters.getCurrentBranch().getName()}' branch " + "until ${gitRebaseParameters.getForkPointCommit().getHash()} commit " + "onto ${gitRebaseParameters.getNewBaseBranch().getName()}"); /* * Git4Idea ({@link git4idea.rebase.GitRebaseUtils#rebase}) does not allow rebasing in detached head state. However, it is * possible with Git (performing checkout implicitly) and should be allowed in the case of "Checkout and Rebase Onto Parent" * Action. To pass the git4idea check in such a case, we checkout the branch explicitly and then perform the actual rebase. */ if (shouldExplicitlyCheckout) { val uiHandler = new GitBranchUiHandlerImpl(project, indicator); new GitBranchWorker(project, Git.getInstance(), uiHandler) .checkout(/* reference */ gitRebaseParameters.getCurrentBranch().getName(), /* detach */ false, Collections.singletonList(gitRepository)); } GitRebaseUtils.rebase(project, Collections.singletonList(gitRepository), params, indicator); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/RenameBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/RenameBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.actions.common.BranchCreationUtils.waitForCreationOfLocalBranch; import static com.virtuslab.gitmachete.frontend.common.WriteActionUtils.blockingRunWriteActionOnUIThread; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.nio.file.Path; import java.util.Collections; import java.util.Objects; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsNotifier; import git4idea.branch.GitBrancher; import git4idea.branch.GitNewBranchOptions; import git4idea.commands.Git; import git4idea.commands.GitCommand; import git4idea.commands.GitCommandResult; import git4idea.commands.GitLineHandler; import git4idea.repo.GitRepository; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot; import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; import com.virtuslab.qual.async.ContinuesInBackground; import com.virtuslab.qual.guieffect.UIThreadUnsafe; @ExtensionMethod({GitVfsUtils.class, Objects.class}) public class RenameBackgroundable extends SideEffectingBackgroundable { private final GitRepository gitRepository; private final BaseEnhancedGraphTable graphTable; private final BranchLayout branchLayout; private final IManagedBranchSnapshot currentBranchSnapshot; private final GitNewBranchOptions gitNewBranchOptions; public RenameBackgroundable( GitRepository gitRepository, BaseEnhancedGraphTable graphTable, BranchLayout branchLayout, IManagedBranchSnapshot currentBranchSnapshot, GitNewBranchOptions gitNewBranchOptions) { super(gitRepository.getProject(), getNonHtmlString("action.GitMachete.RenameBackgroundable.task-title"), "rename"); this.gitRepository = gitRepository; this.graphTable = graphTable; this.branchLayout = branchLayout; this.currentBranchSnapshot = currentBranchSnapshot; this.gitNewBranchOptions = gitNewBranchOptions; } @Override @UIThreadUnsafe @ContinuesInBackground public void doRun(ProgressIndicator indicator) { graphTable.disableEnqueuingUpdates(); Path macheteFilePath = gitRepository.getMacheteFilePath(); val newBranchName = gitNewBranchOptions.getName(); val newBranchLayout = branchLayout.rename(currentBranchSnapshot.getName(), newBranchName); val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class); val gitBrancher = GitBrancher.getInstance(project); gitBrancher.renameBranch(currentBranchSnapshot.getName(), newBranchName, Collections.singletonList(gitRepository)); blockingRunWriteActionOnUIThread(() -> MacheteFileWriter.writeBranchLayout( macheteFilePath, branchLayoutWriter, newBranchLayout, /* backupOldLayout */ true, /* requestor */ this)); // `gitBrancher.renameBranch` continues asynchronously and doesn't allow for passing a callback to execute once complete. // (Stepping deeper is not an option since we would lose some important logic or become very dependent on the internals of git4idea). // Hence, we wait for the creation of the branch (with exponential backoff). waitForCreationOfLocalBranch(gitRepository, newBranchName); if (gitNewBranchOptions.shouldSetTracking()) { val remote = currentBranchSnapshot.getRemoteTrackingBranch(); assert remote != null : "shouldSetTracking is true but the remote branch does not exist"; handleSetTrackingBranch(remote.getRemoteName()); } } @UIThreadUnsafe private void handleSetTrackingBranch(String remoteName) { val newBranchName = gitNewBranchOptions.getName(); val renamedRemoteName = "${remoteName}/${newBranchName}"; // setUpstream: git branch --set-upstream-to <upstreamBranchName> <branchName> val setUpstream = Git.getInstance().setUpstream(gitRepository, renamedRemoteName, newBranchName); var error = setUpstream.getErrorOutputAsJoinedString(); val setUpstreamErrorOutput = setUpstream.getErrorOutput(); if (setUpstream.success()) { // This happens when one renames a branch with a remote branch set up, // and the remote branch with the new name exist. return; } if (!setUpstreamErrorOutput.isEmpty() && setUpstreamErrorOutput.get(0) .equals("fatal: the requested upstream branch '${renamedRemoteName}' does not exist")) { val unsetUpstream = unsetUpstream(newBranchName); val unsetUpstreamErrorOutput = unsetUpstream.getErrorOutput(); if (unsetUpstream.success()) { // the requested upstream branch 'origin/<new-branch-name>' does not exist // hint: // hint: If you are planning on basing your work on an upstream // hint: branch that already exists at the remote, you may need to // hint: run "git fetch" to retrieve it. // hint: // hint: If you are planning to push out a new local branch that // hint: will track its remote counterpart, you may want to use // hint: "git push -u" to set the upstream config as you push. // hint: Disable this message with "git config advice.setUpstreamFailure false" // --- // This happens when one renames a branch with a remote branch set up, // and a local branch with the new name is created for the first time, // and the remote with the new name does not exist. return; } else if (!unsetUpstreamErrorOutput.isEmpty() && unsetUpstreamErrorOutput.get(0) .equals("fatal: Branch '${newBranchName}' has no upstream information")) { // fatal: Branch '<new-branch-name>' has no upstream information // --- // This happens when one renames a branch with a remote branch set up, // and a local branch with the new name is created for the second and next time, // and the remote with the new name does not exist. return; } error = unsetUpstream.getErrorOutputAsJoinedString(); } VcsNotifier.getInstance(project).notifyError(null, getString("action.GitMachete.RenameBackgroundable.rename-failed"), error); } @UIThreadUnsafe private GitCommandResult unsetUpstream(String branchName) { GitLineHandler h = new GitLineHandler(gitRepository.getProject(), gitRepository.getRoot(), GitCommand.BRANCH); h.setStdoutSuppressed(false); h.addParameters("--unset-upstream", branchName); return Git.getInstance().runCommand(h); } @Override @UIEffect public void onThrowable(Throwable e) { val exceptionMessage = e.getMessage(); VcsNotifier.getInstance(project).notifyError(/* displayId */ null, /* title */ getString("action.GitMachete.RenameBackgroundable.notification.title.branch-layout-write-fail"), exceptionMessage.requireNonNullElse("")); } @Override @ContinuesInBackground public void onFinished() { graphTable.enableEnqueuingUpdates(); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SlideInNonRootBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SlideInNonRootBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.util.Objects; import com.intellij.openapi.vcs.VcsNotifier; import git4idea.repo.GitRepository; import lombok.experimental.ExtensionMethod; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutEntry; import com.virtuslab.branchlayout.api.EntryDoesNotExistException; import com.virtuslab.branchlayout.api.EntryIsDescendantOfException; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.gitmachete.frontend.actions.common.SlideInOptions; import com.virtuslab.gitmachete.frontend.actions.common.UiThreadUnsafeRunnable; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; @ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class, Objects.class}) public class SlideInNonRootBackgroundable extends BaseSlideInBackgroundable { private final String parentName; public SlideInNonRootBackgroundable( GitRepository gitRepository, BranchLayout branchLayout, IBranchLayoutWriter branchLayoutWriter, BaseEnhancedGraphTable graphTable, UiThreadUnsafeRunnable preSlideInRunnable, SlideInOptions slideInOptions, String parentName) { super(gitRepository, branchLayout, branchLayoutWriter, graphTable, preSlideInRunnable, slideInOptions); this.parentName = parentName; } @Override @Nullable BranchLayout deriveNewBranchLayout(BranchLayout targetBranchLayout, BranchLayoutEntry entryToSlideIn) { try { return targetBranchLayout.slideIn(parentName, entryToSlideIn); } catch (EntryDoesNotExistException e) { notifyError( getString("action.GitMachete.SlideInNonRootBackgroundable.notification.message.entry-does-not-exist.HTML") .fmt(parentName), e); return null; } catch (EntryIsDescendantOfException e) { notifyError( getString("action.GitMachete.SlideInNonRootBackgroundable.notification.message.entry-is-descendant-of.HTML") .fmt(entryToSlideIn.getName(), parentName), e); return null; } } private void notifyError(@Nullable String message, Throwable throwable) { VcsNotifier.getInstance(project).notifyError(/* displayId */ null, /* title */ getString("action.GitMachete.SlideInNonRootBackgroundable.notification.title.slide-in-fail.HTML") .fmt(slideInOptions.getName()), message.requireNonNullElse(throwable.getMessage().requireNonNullElse(""))); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SlideInRootBackgroundable.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/backgroundables/SlideInRootBackgroundable.java
package com.virtuslab.gitmachete.frontend.actions.backgroundables; import git4idea.repo.GitRepository; import lombok.experimental.ExtensionMethod; import org.checkerframework.checker.nullness.qual.Nullable; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.branchlayout.api.BranchLayoutEntry; import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter; import com.virtuslab.gitmachete.frontend.actions.common.SlideInOptions; import com.virtuslab.gitmachete.frontend.actions.common.UiThreadUnsafeRunnable; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; @ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class}) public class SlideInRootBackgroundable extends BaseSlideInBackgroundable { public SlideInRootBackgroundable( GitRepository gitRepository, BranchLayout branchLayout, IBranchLayoutWriter branchLayoutWriter, BaseEnhancedGraphTable graphTable, UiThreadUnsafeRunnable preSlideInRunnable, SlideInOptions slideInOptions) { super(gitRepository, branchLayout, branchLayoutWriter, graphTable, preSlideInRunnable, slideInOptions); } @Override public @Nullable BranchLayout deriveNewBranchLayout(BranchLayout targetBranchLayout, BranchLayoutEntry entryToSlideIn) { return new BranchLayout(targetBranchLayout.getRootEntries().append(entryToSlideIn)); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseRenameAction.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseRenameAction.java
package com.virtuslab.gitmachete.frontend.actions.base; import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString; import java.util.ArrayList; import java.util.Collections; import com.intellij.openapi.actionSystem.AnActionEvent; import git4idea.branch.GitBranchOperationType; import git4idea.repo.GitRepository; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.branchlayout.api.BranchLayout; import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot; import com.virtuslab.gitmachete.frontend.actions.backgroundables.RenameBackgroundable; import com.virtuslab.gitmachete.frontend.actions.dialogs.MyGitNewBranchDialog; import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; import com.virtuslab.qual.async.ContinuesInBackground; @ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class}) public abstract class BaseRenameAction extends BaseGitMacheteRepositoryReadyAction implements IBranchNameProvider, IExpectsKeyGitMacheteRepository { @Override protected boolean isSideEffecting() { return true; } @Override @UIEffect protected void onUpdate(AnActionEvent anActionEvent) { super.onUpdate(anActionEvent); val presentation = anActionEvent.getPresentation(); if (!presentation.isEnabledAndVisible()) { return; } val branchName = getNameOfBranchUnderAction(anActionEvent); val branch = branchName != null ? getManagedBranchByName(anActionEvent, branchName) : null; if (branch == null) { presentation.setEnabled(false); presentation.setDescription(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch") .fmt("Rename", getQuotedStringOrCurrent(branchName))); } else { presentation.setDescription( getNonHtmlString("action.GitMachete.BaseRenameAction.description").fmt(branch.getName())); } } @Override @ContinuesInBackground @UIEffect public void actionPerformed(AnActionEvent anActionEvent) { val gitRepository = getSelectedGitRepository(anActionEvent); val branchName = getNameOfBranchUnderAction(anActionEvent); val branch = branchName != null ? getManagedBranchByName(anActionEvent, branchName) : null; val branchLayout = getBranchLayout(anActionEvent); val graphTable = getGraphTable(anActionEvent); if (gitRepository == null || branchName == null || branchLayout == null || branch == null || graphTable == null) { return; } rename(gitRepository, graphTable, branch, branchLayout); } @ContinuesInBackground @UIEffect private void rename(GitRepository gitRepository, BaseEnhancedGraphTable graphTable, IManagedBranchSnapshot branch, BranchLayout branchLayout) { val project = gitRepository.getProject(); val remotes = new ArrayList<>(gitRepository.getRemotes()); val gitNewBranchDialog = new MyGitNewBranchDialog(project, Collections.singletonList(gitRepository), getString("action.GitMachete.BaseRenameAction.description").fmt(branch.getName()), branch.getName(), /* showCheckOutOption */ false, /* showResetOption */ false, /* showKeepRemoteOption */ branch.getRemoteTrackingBranch() != null, /* localConflictsAllowed */ false, GitBranchOperationType.RENAME); val options = gitNewBranchDialog.showAndGetOptions(); if (options != null) { new RenameBackgroundable(gitRepository, graphTable, branchLayout, branch, options) .queue(); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/IBranchNameProvider.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/IBranchNameProvider.java
package com.virtuslab.gitmachete.frontend.actions.base; import com.intellij.openapi.actionSystem.AnActionEvent; import org.checkerframework.checker.nullness.qual.Nullable; public interface IBranchNameProvider { @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseCheckoutAction.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseCheckoutAction.java
package com.virtuslab.gitmachete.frontend.actions.base; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import java.util.Collections; import com.intellij.openapi.actionSystem.AnActionEvent; import git4idea.branch.GitBrancher; import lombok.experimental.ExtensionMethod; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.tainting.qual.Untainted; import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName; import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle; import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils; import com.virtuslab.qual.async.ContinuesInBackground; @ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class}) public abstract class BaseCheckoutAction extends BaseGitMacheteRepositoryReadyAction implements IExpectsKeySelectedBranchName { @Override protected boolean isSideEffecting() { return true; } protected abstract @Nullable String getTargetBranchName(AnActionEvent anActionEvent); protected abstract @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent); @Override @UIEffect protected void onUpdate(AnActionEvent anActionEvent) { super.onUpdate(anActionEvent); val presentation = anActionEvent.getPresentation(); if (!presentation.isEnabledAndVisible()) { return; } val targetBranchName = getTargetBranchName(anActionEvent); // It's very unlikely that targetBranchName is empty at this point since it's assigned directly before invoking this // action in EnhancedGraphTable.EnhancedGraphTableMouseAdapter#mouseClicked; still, it's better to be safe. if (targetBranchName == null || targetBranchName.isEmpty()) { presentation.setEnabled(false); presentation.setDescription(getNonExistentBranchMessage(anActionEvent)); return; } val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent); if (currentBranchName != null && currentBranchName.equals(targetBranchName)) { presentation.setEnabled(false); presentation.setDescription( getNonHtmlString("action.GitMachete.BaseCheckoutAction.description.disabled.currently-checked-out") .fmt(targetBranchName)); } else { presentation.setDescription( getNonHtmlString("action.GitMachete.BaseCheckoutAction.description.precise").fmt(targetBranchName)); } } @Override @ContinuesInBackground @UIEffect public void actionPerformed(AnActionEvent anActionEvent) { val targetBranchName = getTargetBranchName(anActionEvent); if (targetBranchName == null || targetBranchName.isEmpty()) { return; } val project = getProject(anActionEvent); val gitRepository = getSelectedGitRepository(anActionEvent); if (gitRepository != null) { log().debug(() -> "Queuing '${targetBranchName}' branch checkout background task"); GitBrancher.getInstance(project).checkout(/* reference */ targetBranchName, /* detach */ false, Collections.singletonList(gitRepository), /* callInAwtLater */ () -> {}); } } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseGitMacheteRepositoryReadyAction.java
frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseGitMacheteRepositoryReadyAction.java
package com.virtuslab.gitmachete.frontend.actions.base; import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import lombok.val; import org.checkerframework.checker.guieffect.qual.UIEffect; import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository; public abstract class BaseGitMacheteRepositoryReadyAction extends BaseProjectDependentAction implements IExpectsKeyGitMacheteRepository { @Override @UIEffect protected void onUpdate(AnActionEvent anActionEvent) { super.onUpdate(anActionEvent); boolean isEnabled = getGitMacheteRepositorySnapshot(anActionEvent) != null; val presentation = anActionEvent.getPresentation(); presentation.setEnabled(isEnabled); if (!isEnabled) { presentation.setDescription( getNonHtmlString( "action.GitMachete.BaseGitMacheteRepositoryReadyAction.description.disabled.undefined.git-machete-repository")); } } /** * Bear in mind that {@link AnAction#beforeActionPerformedUpdate} is called before each action. * (For more details check {@link com.intellij.openapi.actionSystem.ex.ActionUtil} as well). * The {@link AnActionEvent} argument passed to before-called {@link AnAction#update} is the same one that is passed here. * This gives us certainty that all checks from actions' update implementations will be performed * and all data available via data keys in those {@code update} implementations will still be available * in {@link #actionPerformed} implementations. */ @Override @UIEffect public abstract void actionPerformed(AnActionEvent anActionEvent); }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false