diff --git a/plugin/pom.xml b/plugin/pom.xml index 8408cb9..f061866 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -109,5 +109,9 @@ commons-codec provided + + org.slf4j + slf4j-api + \ No newline at end of file diff --git a/plugin/src/main/java/git4idea/actions/GitAbstractRebaseAction.java b/plugin/src/main/java/git4idea/actions/GitAbstractRebaseAction.java index d8fcc61..e2ab831 100644 --- a/plugin/src/main/java/git4idea/actions/GitAbstractRebaseAction.java +++ b/plugin/src/main/java/git4idea/actions/GitAbstractRebaseAction.java @@ -28,7 +28,6 @@ import git4idea.rebase.GitRebaseActionDialog; import git4idea.rebase.GitRebaseUtils; import git4idea.repo.GitRepository; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -102,7 +101,8 @@ private GitRepository chooseRepository(@Nonnull Project project, @Nonnull Collec return firstRepo; } List roots = new ArrayList<>(getRootsFromRepositories(repositories)); - GitRebaseActionDialog dialog = new GitRebaseActionDialog(project, getTemplatePresentation().getText(), roots, firstRepo.getRoot()); + GitRebaseActionDialog dialog = + new GitRebaseActionDialog(project, getTemplatePresentation().getTextValue(), roots, firstRepo.getRoot()); dialog.show(); VirtualFile root = dialog.selectRoot(); if (root == null) { diff --git a/plugin/src/main/java/git4idea/crlf/GitCrlfDialog.java b/plugin/src/main/java/git4idea/crlf/GitCrlfDialog.java index 0f59713..bcaaae8 100644 --- a/plugin/src/main/java/git4idea/crlf/GitCrlfDialog.java +++ b/plugin/src/main/java/git4idea/crlf/GitCrlfDialog.java @@ -15,6 +15,7 @@ */ package git4idea.crlf; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.ui.ex.awt.*; import consulo.webBrowser.BrowserUtil; @@ -36,75 +37,71 @@ * @see GitCrlfProblemsDetector */ public class GitCrlfDialog extends DialogWrapper { - - public static final int SET = DialogWrapper.OK_EXIT_CODE; - public static final int DONT_SET = DialogWrapper.NEXT_USER_EXIT_CODE; - public static final int CANCEL = DialogWrapper.CANCEL_EXIT_CODE; - private JBCheckBox myDontWarn; - - public GitCrlfDialog(@Nullable Project project) { - super(project, false); - - setOKButtonText("Fix and Commit"); - setCancelButtonText("Cancel"); - setTitle("Line Separators Warning"); - getCancelAction().putValue(DialogWrapper.FOCUSED_ACTION, true); - - init(); - } - - @Nonnull - @Override - protected Action[] createActions() { - return new Action[] { getHelpAction(), getOKAction(), getCancelAction(), new DialogWrapperExitAction("Commit As Is", DONT_SET) }; - } - - @Override - protected JComponent createCenterPanel() { - JLabel description = new JBLabel( - "You are about to commit CRLF line separators to the Git repository.
" + - "It is recommended to set core.autocrlf Git attribute to " + RECOMMENDED_VALUE + - " to avoid line separator issues."); - - JLabel additionalDescription = new JBLabel( - "Fix and Commit: git config --global core.autocrlf " + RECOMMENDED_VALUE + " will be called,
" + - "Commit as Is: the config value won't be set.", UIUtil.ComponentStyle.SMALL); - - JLabel readMore = new LinkLabel("Read more", null, new LinkListener() { - @Override - public void linkSelected(LinkLabel aSource, Object aLinkData) { - BrowserUtil.browse("https://help.github.com/articles/dealing-with-line-endings"); - } - }); - - JLabel icon = new JBLabel(UIUtil.getWarningIcon(), SwingConstants.LEFT); - myDontWarn = new JBCheckBox("Don't warn again"); - myDontWarn.setMnemonic('w'); - - JPanel rootPanel = new JPanel(new GridBagLayout()); - GridBag g = new GridBag() - .setDefaultInsets(new Insets(0, 6, DEFAULT_VGAP, DEFAULT_HGAP)) - .setDefaultAnchor(GridBagConstraints.LINE_START) - .setDefaultFill(GridBagConstraints.HORIZONTAL); - - rootPanel.add(icon, g.nextLine().next().coverColumn(4)); - rootPanel.add(description, g.next()); - rootPanel.add(readMore, g.nextLine().next().next()); - rootPanel.add(additionalDescription, g.nextLine().next().next().pady(DEFAULT_HGAP)); - rootPanel.add(myDontWarn, g.nextLine().next().next().insets(0, 0, 0, 0)); - - return rootPanel; - - } - - public boolean dontWarnAgain() { - return myDontWarn.isSelected(); - } - - @Nullable - @Override - protected String getHelpId() { - return "reference.VersionControl.Git.CrlfWarning"; - } - + public static final int SET = DialogWrapper.OK_EXIT_CODE; + public static final int DONT_SET = DialogWrapper.NEXT_USER_EXIT_CODE; + public static final int CANCEL = DialogWrapper.CANCEL_EXIT_CODE; + private JBCheckBox myDontWarn; + + public GitCrlfDialog(@Nullable Project project) { + super(project, false); + + setOKButtonText(LocalizeValue.localizeTODO("Fix and Commit")); + setCancelButtonText(LocalizeValue.localizeTODO("Cancel")); + setTitle(LocalizeValue.localizeTODO("Line Separators Warning")); + getCancelAction().putValue(DialogWrapper.FOCUSED_ACTION, true); + + init(); + } + + @Nonnull + @Override + protected Action[] createActions() { + return new Action[]{getHelpAction(), getOKAction(), getCancelAction(), new DialogWrapperExitAction("Commit As Is", DONT_SET)}; + } + + @Override + protected JComponent createCenterPanel() { + JLabel description = new JBLabel( + "You are about to commit CRLF line separators to the Git repository.
" + + "It is recommended to set core.autocrlf Git attribute to " + RECOMMENDED_VALUE + + " to avoid line separator issues."); + + JLabel additionalDescription = new JBLabel( + "Fix and Commit: git config --global core.autocrlf " + RECOMMENDED_VALUE + " will be called,
" + + "Commit as Is: the config value won't be set.", UIUtil.ComponentStyle.SMALL); + + JLabel readMore = new LinkLabel<>( + "Read more", + null, + (aSource, aLinkData) -> BrowserUtil.browse("https://help.github.com/articles/dealing-with-line-endings") + ); + + JLabel icon = new JBLabel(UIUtil.getWarningIcon(), SwingConstants.LEFT); + myDontWarn = new JBCheckBox("Don't warn again"); + myDontWarn.setMnemonic('w'); + + JPanel rootPanel = new JPanel(new GridBagLayout()); + GridBag g = new GridBag() + .setDefaultInsets(JBUI.insets(0, 6, DEFAULT_VGAP, DEFAULT_HGAP)) + .setDefaultAnchor(GridBagConstraints.LINE_START) + .setDefaultFill(GridBagConstraints.HORIZONTAL); + + rootPanel.add(icon, g.nextLine().next().coverColumn(4)); + rootPanel.add(description, g.next()); + rootPanel.add(readMore, g.nextLine().next().next()); + rootPanel.add(additionalDescription, g.nextLine().next().next().pady(DEFAULT_HGAP)); + rootPanel.add(myDontWarn, g.nextLine().next().next().insets(0, 0, 0, 0)); + + return rootPanel; + } + + public boolean dontWarnAgain() { + return myDontWarn.isSelected(); + } + + @Nullable + @Override + protected String getHelpId() { + return "reference.VersionControl.Git.CrlfWarning"; + } } diff --git a/plugin/src/main/java/git4idea/crlf/GitCrlfProblemsDetector.java b/plugin/src/main/java/git4idea/crlf/GitCrlfProblemsDetector.java index c2362cf..806d558 100644 --- a/plugin/src/main/java/git4idea/crlf/GitCrlfProblemsDetector.java +++ b/plugin/src/main/java/git4idea/crlf/GitCrlfProblemsDetector.java @@ -28,19 +28,19 @@ import git4idea.config.GitConfigUtil; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; - import jakarta.annotation.Nonnull; + import java.util.*; /** * Given a number of files, detects if CRLF line separators in them are about to be committed to Git. That is: * * All checks are made only for Windows system. * @@ -51,140 +51,141 @@ */ public class GitCrlfProblemsDetector { - private static final Logger LOG = Logger.getInstance(GitCrlfProblemsDetector.class); - private static final String CRLF = "\r\n"; + private static final Logger LOG = Logger.getInstance(GitCrlfProblemsDetector.class); + private static final String CRLF = "\r\n"; - @Nonnull - private final Project myProject; - @Nonnull - private final Git myGit; + @Nonnull + private final Project myProject; + @Nonnull + private final Git myGit; - private final boolean myShouldWarn; + private final boolean myShouldWarn; - @Nonnull - public static GitCrlfProblemsDetector detect(@Nonnull Project project, @Nonnull Git git, @Nonnull Collection files) { - return new GitCrlfProblemsDetector(project, git, files); - } + @Nonnull + public static GitCrlfProblemsDetector detect(@Nonnull Project project, @Nonnull Git git, @Nonnull Collection files) { + return new GitCrlfProblemsDetector(project, git, files); + } - private GitCrlfProblemsDetector(@Nonnull Project project, @Nonnull Git git, @Nonnull Collection files) { - myProject = project; - myGit = git; + private GitCrlfProblemsDetector(@Nonnull Project project, @Nonnull Git git, @Nonnull Collection files) { + myProject = project; + myGit = git; - Map> filesByRoots = sortFilesByRoots(files); + Map> filesByRoots = sortFilesByRoots(files); - boolean shouldWarn = false; - Collection rootsWithIncorrectAutoCrlf = getRootsWithIncorrectAutoCrlf(filesByRoots); - if (!rootsWithIncorrectAutoCrlf.isEmpty()) { - Map> crlfFilesByRoots = findFilesWithCrlf(filesByRoots, rootsWithIncorrectAutoCrlf); - if (!crlfFilesByRoots.isEmpty()) { - Map> crlfFilesWithoutAttrsByRoots = findFilesWithoutAttrs(crlfFilesByRoots); - shouldWarn = !crlfFilesWithoutAttrsByRoots.isEmpty(); - } - } - myShouldWarn = shouldWarn; - } - - private Map> findFilesWithoutAttrs(Map> filesByRoots) { - Map> filesWithoutAttrsByRoot = new HashMap>(); - for (Map.Entry> entry : filesByRoots.entrySet()) { - VirtualFile root = entry.getKey(); - Collection files = entry.getValue(); - Collection filesWithoutAttrs = findFilesWithoutAttrs(root, files); - if (!filesWithoutAttrs.isEmpty()) { - filesWithoutAttrsByRoot.put(root, filesWithoutAttrs); - } - } - return filesWithoutAttrsByRoot; - } - - @Nonnull - private Collection findFilesWithoutAttrs(@Nonnull VirtualFile root, @Nonnull Collection files) { - GitRepository repository = GitRepositoryManager.getInstance(myProject).getRepositoryForRoot(root); - if (repository == null) { - LOG.warn("Repository is null for " + root); - return Collections.emptyList(); - } - Collection interestingAttributes = Arrays.asList(GitAttribute.TEXT.getName(), GitAttribute.CRLF.getName()); - GitCommandResult result = myGit.checkAttr(repository, interestingAttributes, files); - if (!result.success()) { - LOG.warn(String.format("Couldn't git check-attr. Attributes: %s, files: %s", interestingAttributes, files)); - return Collections.emptyList(); + boolean shouldWarn = false; + Collection rootsWithIncorrectAutoCrlf = getRootsWithIncorrectAutoCrlf(filesByRoots); + if (!rootsWithIncorrectAutoCrlf.isEmpty()) { + Map> crlfFilesByRoots = findFilesWithCrlf(filesByRoots, rootsWithIncorrectAutoCrlf); + if (!crlfFilesByRoots.isEmpty()) { + Map> crlfFilesWithoutAttrsByRoots = findFilesWithoutAttrs(crlfFilesByRoots); + shouldWarn = !crlfFilesWithoutAttrsByRoots.isEmpty(); + } + } + myShouldWarn = shouldWarn; } - GitCheckAttrParser parser = GitCheckAttrParser.parse(result.getOutput()); - Map> attributes = parser.getAttributes(); - Collection filesWithoutAttrs = new ArrayList(); - for (VirtualFile file : files) { - ProgressIndicatorProvider.checkCanceled(); - String relativePath = FileUtil.getRelativePath(root.getPath(), file.getPath(), '/'); - Collection attrs = attributes.get(relativePath); - if (attrs == null || !attrs.contains(GitAttribute.TEXT) && !attrs.contains(GitAttribute.CRLF)) { - filesWithoutAttrs.add(file); - } + + private Map> findFilesWithoutAttrs(Map> filesByRoots) { + Map> filesWithoutAttrsByRoot = new HashMap<>(); + for (Map.Entry> entry : filesByRoots.entrySet()) { + VirtualFile root = entry.getKey(); + Collection files = entry.getValue(); + Collection filesWithoutAttrs = findFilesWithoutAttrs(root, files); + if (!filesWithoutAttrs.isEmpty()) { + filesWithoutAttrsByRoot.put(root, filesWithoutAttrs); + } + } + return filesWithoutAttrsByRoot; } - return filesWithoutAttrs; - } - - @Nonnull - private Map> findFilesWithCrlf(@Nonnull Map> allFilesByRoots, - @Nonnull Collection rootsWithIncorrectAutoCrlf) { - Map> filesWithCrlfByRoots = new HashMap>(); - for (Map.Entry> entry : allFilesByRoots.entrySet()) { - VirtualFile root = entry.getKey(); - List files = entry.getValue(); - if (rootsWithIncorrectAutoCrlf.contains(root)) { - Collection filesWithCrlf = findFilesWithCrlf(files); - if (!filesWithCrlf.isEmpty()) { - filesWithCrlfByRoots.put(root, filesWithCrlf); + + @Nonnull + private Collection findFilesWithoutAttrs(@Nonnull VirtualFile root, @Nonnull Collection files) { + GitRepository repository = GitRepositoryManager.getInstance(myProject).getRepositoryForRoot(root); + if (repository == null) { + LOG.warn("Repository is null for " + root); + return Collections.emptyList(); + } + Collection interestingAttributes = Arrays.asList(GitAttribute.TEXT.getName(), GitAttribute.CRLF.getName()); + GitCommandResult result = myGit.checkAttr(repository, interestingAttributes, files); + if (!result.success()) { + LOG.warn(String.format("Couldn't git check-attr. Attributes: %s, files: %s", interestingAttributes, files)); + return Collections.emptyList(); } - } + GitCheckAttrParser parser = GitCheckAttrParser.parse(result.getOutput()); + Map> attributes = parser.getAttributes(); + Collection filesWithoutAttrs = new ArrayList<>(); + for (VirtualFile file : files) { + ProgressIndicatorProvider.checkCanceled(); + String relativePath = FileUtil.getRelativePath(root.getPath(), file.getPath(), '/'); + Collection attrs = attributes.get(relativePath); + if (attrs == null || !attrs.contains(GitAttribute.TEXT) && !attrs.contains(GitAttribute.CRLF)) { + filesWithoutAttrs.add(file); + } + } + return filesWithoutAttrs; } - return filesWithCrlfByRoots; - } - - @Nonnull - private Collection findFilesWithCrlf(@Nonnull Collection files) { - Collection filesWithCrlf = new ArrayList(); - for (VirtualFile file : files) { - ProgressIndicatorProvider.checkCanceled(); - String separator = file.getDetectedLineSeparator(); - if (CRLF.equals(separator)) { - filesWithCrlf.add(file); - } + + @Nonnull + private Map> findFilesWithCrlf( + @Nonnull Map> allFilesByRoots, + @Nonnull Collection rootsWithIncorrectAutoCrlf + ) { + Map> filesWithCrlfByRoots = new HashMap<>(); + for (Map.Entry> entry : allFilesByRoots.entrySet()) { + VirtualFile root = entry.getKey(); + List files = entry.getValue(); + if (rootsWithIncorrectAutoCrlf.contains(root)) { + Collection filesWithCrlf = findFilesWithCrlf(files); + if (!filesWithCrlf.isEmpty()) { + filesWithCrlfByRoots.put(root, filesWithCrlf); + } + } + } + return filesWithCrlfByRoots; } - return filesWithCrlf; - } - - @Nonnull - private Collection getRootsWithIncorrectAutoCrlf(@Nonnull Map> filesByRoots) { - Collection rootsWithIncorrectAutoCrlf = new ArrayList(); - for (Map.Entry> entry : filesByRoots.entrySet()) { - VirtualFile root = entry.getKey(); - boolean autocrlf = isAutoCrlfSetRight(root); - if (!autocrlf) { - rootsWithIncorrectAutoCrlf.add(root); - } + + @Nonnull + private Collection findFilesWithCrlf(@Nonnull Collection files) { + Collection filesWithCrlf = new ArrayList<>(); + for (VirtualFile file : files) { + ProgressIndicatorProvider.checkCanceled(); + String separator = file.getDetectedLineSeparator(); + if (CRLF.equals(separator)) { + filesWithCrlf.add(file); + } + } + return filesWithCrlf; } - return rootsWithIncorrectAutoCrlf; - } - - private boolean isAutoCrlfSetRight(@Nonnull VirtualFile root) { - GitRepository repository = GitRepositoryManager.getInstance(myProject).getRepositoryForRoot(root); - if (repository == null) { - LOG.warn("Repository is null for " + root); - return true; + + @Nonnull + private Collection getRootsWithIncorrectAutoCrlf(@Nonnull Map> filesByRoots) { + Collection rootsWithIncorrectAutoCrlf = new ArrayList<>(); + for (Map.Entry> entry : filesByRoots.entrySet()) { + VirtualFile root = entry.getKey(); + boolean autocrlf = isAutoCrlfSetRight(root); + if (!autocrlf) { + rootsWithIncorrectAutoCrlf.add(root); + } + } + return rootsWithIncorrectAutoCrlf; } - GitCommandResult result = myGit.config(repository, GitConfigUtil.CORE_AUTOCRLF); - String value = result.getOutputAsJoinedString(); - return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("input"); - } - @Nonnull - private static Map> sortFilesByRoots(@Nonnull Collection files) { - return GitUtil.sortFilesByGitRootsIgnoringOthers(files); - } + private boolean isAutoCrlfSetRight(@Nonnull VirtualFile root) { + GitRepository repository = GitRepositoryManager.getInstance(myProject).getRepositoryForRoot(root); + if (repository == null) { + LOG.warn("Repository is null for " + root); + return true; + } + GitCommandResult result = myGit.config(repository, GitConfigUtil.CORE_AUTOCRLF); + String value = result.getOutputAsJoinedString(); + return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("input"); + } - public boolean shouldWarn() { - return myShouldWarn; - } + @Nonnull + private static Map> sortFilesByRoots(@Nonnull Collection files) { + return GitUtil.sortFilesByGitRootsIgnoringOthers(files); + } + public boolean shouldWarn() { + return myShouldWarn; + } } diff --git a/plugin/src/main/java/git4idea/crlf/GitCrlfUtil.java b/plugin/src/main/java/git4idea/crlf/GitCrlfUtil.java index 43c6f92..cebd021 100644 --- a/plugin/src/main/java/git4idea/crlf/GitCrlfUtil.java +++ b/plugin/src/main/java/git4idea/crlf/GitCrlfUtil.java @@ -15,13 +15,11 @@ */ package git4idea.crlf; -import consulo.application.util.SystemInfo; +import consulo.platform.Platform; /** * @author Kirill Likhodedov */ public class GitCrlfUtil { - - public static final String RECOMMENDED_VALUE = SystemInfo.isWindows ? "true" : "input"; - + public static final String RECOMMENDED_VALUE = Platform.current().os().isWindows() ? "true" : "input"; } diff --git a/plugin/src/main/java/git4idea/diff/GitDiffProvider.java b/plugin/src/main/java/git4idea/diff/GitDiffProvider.java index 9951a94..442d1ff 100644 --- a/plugin/src/main/java/git4idea/diff/GitDiffProvider.java +++ b/plugin/src/main/java/git4idea/diff/GitDiffProvider.java @@ -45,7 +45,10 @@ import jakarta.inject.Inject; import jakarta.inject.Singleton; -import java.util.*; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; /** * Git diff provider @@ -62,9 +65,7 @@ public class GitDiffProvider implements DiffProvider { * The status manager for the project */ private final FileStatusManager myStatusManager; - /** - * - */ + private static final Set ourGoodStatuses; static { @@ -108,7 +109,7 @@ public VcsRevisionNumber getCurrentRevision(VirtualFile file) { @Nullable @Override - public VcsRevisionDescription getCurrentRevisionDescription(final VirtualFile file) { + public VcsRevisionDescription getCurrentRevisionDescription(@Nonnull VirtualFile file) { if (file.isDirectory()) { return null; } @@ -149,7 +150,7 @@ public ContentRevision createFileContent(VcsRevisionNumber revisionNumber, Virtu if (selectedFile.isDirectory()) { return null; } - final String path = selectedFile.getPath(); + String path = selectedFile.getPath(); if (GitUtil.gitRootOrNull(selectedFile) == null) { return null; } @@ -157,8 +158,8 @@ public ContentRevision createFileContent(VcsRevisionNumber revisionNumber, Virtu // faster, if there were no renames FilePath filePath = VcsUtil.getFilePath(path); try { - final CommittedChangesProvider committedChangesProvider = GitVcs.getInstance(myProject).getCommittedChangesProvider(); - final Pair pair = committedChangesProvider.getOneList(selectedFile, revisionNumber); + CommittedChangesProvider committedChangesProvider = GitVcs.getInstance(myProject).getCommittedChangesProvider(); + Pair pair = committedChangesProvider.getOneList(selectedFile, revisionNumber); if (pair != null) { return GitContentRevision.createRevision(pair.getSecond(), revisionNumber, myProject, selectedFile.getCharset()); } @@ -195,11 +196,9 @@ public ItemLatestState getLastRevision(FilePath filePath) { if (filePath.isDirectory()) { return null; } - final VirtualFile vf = filePath.getVirtualFile(); - if (vf != null) { - if (!ourGoodStatuses.contains(myStatusManager.getStatus(vf))) { - return null; - } + VirtualFile vf = filePath.getVirtualFile(); + if (vf != null && !ourGoodStatuses.contains(myStatusManager.getStatus(vf))) { + return null; } try { return GitHistoryUtils.getLastRevision(myProject, filePath); diff --git a/plugin/src/main/java/git4idea/log/GitBekParentFixer.java b/plugin/src/main/java/git4idea/log/GitBekParentFixer.java index bb32262..c72ff46 100644 --- a/plugin/src/main/java/git4idea/log/GitBekParentFixer.java +++ b/plugin/src/main/java/git4idea/log/GitBekParentFixer.java @@ -18,6 +18,7 @@ import consulo.util.collection.ContainerUtil; import consulo.versionControlSystem.VcsException; import consulo.versionControlSystem.log.*; +import consulo.versionControlSystem.log.graph.GraphCommit; import consulo.versionControlSystem.log.util.BekUtil; import consulo.virtualFileSystem.VirtualFile; import jakarta.annotation.Nonnull; @@ -59,7 +60,7 @@ TimedVcsCommit fixCommit(@Nonnull TimedVcsCommit commit) { @Nonnull private static Set getWrongCommits(@Nonnull GitLogProvider provider, @Nonnull VirtualFile root) throws VcsException { List commitsMatchingFilter = provider.getCommitsMatchingFilter(root, MAGIC_FILTER, -1); - return ContainerUtil.map2Set(commitsMatchingFilter, timedVcsCommit -> timedVcsCommit.getId()); + return ContainerUtil.map2Set(commitsMatchingFilter, GraphCommit::getId); } @Nonnull @@ -127,7 +128,7 @@ public VcsLogDateFilter getDateFilter() { return null; } - @Nullable + @Nonnull @Override public VcsLogTextFilter getTextFilter() { return textFilter; diff --git a/plugin/src/main/java/git4idea/log/RefParser.java b/plugin/src/main/java/git4idea/log/RefParser.java index b51d9c1..6927814 100644 --- a/plugin/src/main/java/git4idea/log/RefParser.java +++ b/plugin/src/main/java/git4idea/log/RefParser.java @@ -7,79 +7,66 @@ import consulo.virtualFileSystem.VirtualFile; import git4idea.repo.GitRepositoryReader; import jakarta.annotation.Nonnull; - import jakarta.annotation.Nullable; + import java.util.ArrayList; import java.util.Collections; import java.util.List; - /** * TODO: remove when tags are supported by the {@link GitRepositoryReader}. * * @author erokhins */ -class RefParser -{ - private final VcsLogObjectsFactory myFactory; +class RefParser { + private final VcsLogObjectsFactory myFactory; - public RefParser(VcsLogObjectsFactory factory) - { - myFactory = factory; - } + public RefParser(VcsLogObjectsFactory factory) { + myFactory = factory; + } - // e25b7d8f (HEAD, refs/remotes/origin/master, refs/remotes/origin/HEAD, refs/heads/master) - public List parseCommitRefs(@Nonnull String input, @Nonnull VirtualFile root) - { - int firstSpaceIndex = input.indexOf(' '); - if(firstSpaceIndex < 0) - { - return Collections.emptyList(); - } - String strHash = input.substring(0, firstSpaceIndex); - Hash hash = HashImpl.build(strHash); - String refPaths = input.substring(firstSpaceIndex + 2, input.length() - 1); - String[] longRefPaths = refPaths.split(", "); - List refs = new ArrayList(); - for(String longRefPatch : longRefPaths) - { - VcsRef ref = createRef(hash, longRefPatch, root); - if(ref != null) - { - refs.add(ref); - } - } - return refs; - } + // e25b7d8f (HEAD, refs/remotes/origin/master, refs/remotes/origin/HEAD, refs/heads/master) + public List parseCommitRefs(@Nonnull String input, @Nonnull VirtualFile root) { + int firstSpaceIndex = input.indexOf(' '); + if (firstSpaceIndex < 0) { + return Collections.emptyList(); + } + String strHash = input.substring(0, firstSpaceIndex); + Hash hash = HashImpl.build(strHash); + String refPaths = input.substring(firstSpaceIndex + 2, input.length() - 1); + String[] longRefPaths = refPaths.split(", "); + List refs = new ArrayList<>(); + for (String longRefPatch : longRefPaths) { + VcsRef ref = createRef(hash, longRefPatch, root); + if (ref != null) { + refs.add(ref); + } + } + return refs; + } - @Nullable - private static String getRefName(@Nonnull String longRefPath, @Nonnull String startPatch) - { - String tagPrefix = "tag: "; - if(longRefPath.startsWith(tagPrefix)) - { - longRefPath = longRefPath.substring(tagPrefix.length()); - } - if(longRefPath.startsWith(startPatch)) - { - return longRefPath.substring(startPatch.length()); - } - else - { - return null; - } - } + @Nullable + private static String getRefName(@Nonnull String longRefPath, @Nonnull String startPatch) { + String tagPrefix = "tag: "; + if (longRefPath.startsWith(tagPrefix)) { + longRefPath = longRefPath.substring(tagPrefix.length()); + } + if (longRefPath.startsWith(startPatch)) { + return longRefPath.substring(startPatch.length()); + } + else { + return null; + } + } - // example input: fb29c80 refs/tags/92.29 - @Nullable - private VcsRef createRef(@Nonnull Hash hash, @Nonnull String longRefPath, @Nonnull VirtualFile root) - { - String name = getRefName(longRefPath, "refs/tags/"); - if(name != null) - { - return myFactory.createRef(hash, name, GitRefManager.TAG, root); - } + // example input: fb29c80 refs/tags/92.29 + @Nullable + private VcsRef createRef(@Nonnull Hash hash, @Nonnull String longRefPath, @Nonnull VirtualFile root) { + String name = getRefName(longRefPath, "refs/tags/"); + if (name != null) { + return myFactory.createRef(hash, name, GitRefManager.TAG, root); + } - return null; - } + return null; + } } diff --git a/plugin/src/main/java/git4idea/merge/GitMergeCommittingConflictResolver.java b/plugin/src/main/java/git4idea/merge/GitMergeCommittingConflictResolver.java index 68c7a8b..d46fb60 100644 --- a/plugin/src/main/java/git4idea/merge/GitMergeCommittingConflictResolver.java +++ b/plugin/src/main/java/git4idea/merge/GitMergeCommittingConflictResolver.java @@ -19,8 +19,8 @@ import consulo.versionControlSystem.VcsException; import consulo.virtualFileSystem.VirtualFile; import git4idea.commands.Git; - import jakarta.annotation.Nonnull; + import java.util.Collection; /** @@ -29,25 +29,32 @@ * @author Kirill Likhodedov */ public class GitMergeCommittingConflictResolver extends GitConflictResolver { - private final Collection myMergingRoots; - private final boolean myRefreshAfterCommit; - private final GitMerger myMerger; + private final Collection myMergingRoots; + private final boolean myRefreshAfterCommit; + private final GitMerger myMerger; - public GitMergeCommittingConflictResolver(Project project, @Nonnull Git git, GitMerger merger, Collection mergingRoots, - Params params, boolean refreshAfterCommit) { - super(project, git, mergingRoots, params); - myMerger = merger; - myMergingRoots = mergingRoots; - myRefreshAfterCommit = refreshAfterCommit; - } + public GitMergeCommittingConflictResolver( + Project project, + @Nonnull Git git, + GitMerger merger, + Collection mergingRoots, + Params params, + boolean refreshAfterCommit + ) { + super(project, git, mergingRoots, params); + myMerger = merger; + myMergingRoots = mergingRoots; + myRefreshAfterCommit = refreshAfterCommit; + } - @Override protected boolean proceedAfterAllMerged() throws VcsException { - myMerger.mergeCommit(myMergingRoots); - if (myRefreshAfterCommit) { - for (VirtualFile root : myMergingRoots) { - root.refresh(true, true); - } + @Override + protected boolean proceedAfterAllMerged() throws VcsException { + myMerger.mergeCommit(myMergingRoots); + if (myRefreshAfterCommit) { + for (VirtualFile root : myMergingRoots) { + root.refresh(true, true); + } + } + return true; } - return true; - } } diff --git a/plugin/src/main/java/git4idea/merge/GitMergeDialog.form b/plugin/src/main/java/git4idea/merge/GitMergeDialog.form deleted file mode 100644 index 2bf1c35..0000000 --- a/plugin/src/main/java/git4idea/merge/GitMergeDialog.form +++ /dev/null @@ -1,160 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/merge/GitMergeDialog.java b/plugin/src/main/java/git4idea/merge/GitMergeDialog.java index c117b0d..23c4e99 100644 --- a/plugin/src/main/java/git4idea/merge/GitMergeDialog.java +++ b/plugin/src/main/java/git4idea/merge/GitMergeDialog.java @@ -15,10 +15,14 @@ */ package git4idea.merge; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; import consulo.git.localize.GitLocalize; import consulo.project.Project; import consulo.ui.ex.awt.DialogWrapper; import consulo.ui.ex.awt.ElementsChooser; +import consulo.ui.ex.awt.JBUI; import consulo.versionControlSystem.VcsException; import consulo.virtualFileSystem.VirtualFile; import git4idea.GitVcs; @@ -86,7 +90,6 @@ public class GitMergeDialog extends DialogWrapper { private final Project myProject; private final GitVcs myVcs; - /** * A constructor * @@ -127,7 +130,7 @@ private void initBranchChooser() { myBranchChooser = new ElementsChooser<>(true); myBranchChooser.setToolTipText(GitLocalize.mergeBranchesTooltip().get()); GridBagConstraints c = new GridBagConstraints(); - c.insets = new Insets(0, 0, 0, 0); + c.insets = JBUI.emptyInsets(); c.gridx = 0; c.gridy = 0; c.weightx = 1; @@ -136,7 +139,7 @@ private void initBranchChooser() { myBranchToMergeContainer.add(myBranchChooser, c); myStrategy.setRenderer(GitMergeStrategy.LIST_CELL_RENDERER); GitMergeUtil.setupStrategies(myBranchChooser, myStrategy); - final ElementsChooser.ElementsMarkListener listener = + ElementsChooser.ElementsMarkListener listener = (element, isMarked) -> setOKActionEnabled(!myBranchChooser.getMarkedElements().isEmpty()); listener.elementMarkChanged(null, true); myBranchChooser.addElementsMarkListener(listener); @@ -166,7 +169,7 @@ public GitLineHandler handler() { if (!isOK()) { throw new IllegalStateException("The handler could be retrieved only if dialog was completed successfully."); } - VirtualFile root = (VirtualFile)myGitRoot.getSelectedItem(); + VirtualFile root = (VirtualFile) myGitRoot.getSelectedItem(); GitLineHandler h = new GitLineHandler(myProject, root, GitCommand.MERGE); // ignore merge failure h.ignoreErrorCode(1); @@ -176,7 +179,7 @@ public GitLineHandler handler() { if (myAddLogInformationCheckBox.isSelected()) { h.addParameters("--log"); } - final String msg = myCommitMessage.getText().trim(); + String msg = myCommitMessage.getText().trim(); if (msg.length() != 0) { h.addParameters("-m", msg); } @@ -186,7 +189,7 @@ public GitLineHandler handler() { if (myNoFastForwardCheckBox.isSelected()) { h.addParameters("--no-ff"); } - GitMergeStrategy strategy = (GitMergeStrategy)myStrategy.getSelectedItem(); + GitMergeStrategy strategy = (GitMergeStrategy) myStrategy.getSelectedItem(); strategy.addParametersTo(h); for (String branch : myBranchChooser.getMarkedElements()) { h.addParameters(branch); @@ -223,6 +226,427 @@ protected String getHelpId() { * @return selected root */ public VirtualFile getSelectedRoot() { - return (VirtualFile)myGitRoot.getSelectedItem(); + return (VirtualFile) myGitRoot.getSelectedItem(); + } + + { +// GUI initializer generated by Consulo GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + myPanel = new JPanel(); + myPanel.setLayout(new GridLayoutManager(6, 3, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.commonGitRoot().get()); + myPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myGitRoot = new JComboBox(); + myGitRoot.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myPanel.add( + myGitRoot, + new GridConstraints( + 0, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.mergeBranches().get()); + myPanel.add( + label2, + new GridConstraints( + 2, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTHWEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label3 = new JLabel(); + this.$$$loadLabelText$$$(label3, GitLocalize.commonCurrentBranch().get()); + myPanel.add( + label3, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(2, 3, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel1, + new GridConstraints( + 4, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myNoCommitCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myNoCommitCheckBox, GitLocalize.mergeNoCommit().get()); + myNoCommitCheckBox.setToolTipText(GitLocalize.mergeNoCommitTooltip().get()); + panel1.add( + myNoCommitCheckBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myNoFastForwardCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myNoFastForwardCheckBox, GitLocalize.mergeNoFastForward().get()); + myNoFastForwardCheckBox.setToolTipText(GitLocalize.mergeNoFastForwardTooltip().get()); + panel1.add( + myNoFastForwardCheckBox, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + mySquashCommitCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(mySquashCommitCheckBox, GitLocalize.mergeSquashCommit().get()); + mySquashCommitCheckBox.setToolTipText(GitLocalize.mergeSquashTooltip().get()); + panel1.add( + mySquashCommitCheckBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + panel1.add( + spacer1, + new GridConstraints( + 0, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + myAddLogInformationCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myAddLogInformationCheckBox, GitLocalize.mergeAddLogInformation().get()); + myAddLogInformationCheckBox.setToolTipText(GitLocalize.mergeAddLogInformationTooltip().get()); + panel1.add( + myAddLogInformationCheckBox, + new GridConstraints( + 1, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myCurrentBranchText = new JLabel(); + myCurrentBranchText.setText(""); + myCurrentBranchText.setToolTipText(GitLocalize.commonCurrentBranchTooltip().get()); + myPanel.add( + myCurrentBranchText, + new GridConstraints( + 1, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myBranchToMergeContainer = new JPanel(); + myBranchToMergeContainer.setLayout(new GridBagLayout()); + myPanel.add( + myBranchToMergeContainer, + new GridConstraints( + 2, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + JLabel label4 = new JLabel(); + this.$$$loadLabelText$$$(label4, GitLocalize.mergeCommitMessage().get()); + label4.setVerticalAlignment(0); + myPanel.add( + label4, + new GridConstraints( + 5, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTHWEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label5 = new JLabel(); + this.$$$loadLabelText$$$(label5, GitLocalize.mergeStrategy().get()); + myPanel.add( + label5, + new GridConstraints( + 3, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myCommitMessage = new JTextField(); + myCommitMessage.setToolTipText(GitLocalize.mergeCommitMessageTooltip().get()); + myPanel.add( + myCommitMessage, + new GridConstraints( + 5, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + new Dimension(150, -1), + null, + 0, + false + ) + ); + myStrategy = new JComboBox<>(); + myStrategy.setEnabled(false); + myStrategy.setToolTipText(GitLocalize.mergeStrategyTooltip().get()); + myPanel.add( + myStrategy, + new GridConstraints( + 3, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer2 = new Spacer(); + myPanel.add( + spacer2, + new GridConstraints( + 3, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + label1.setLabelFor(myGitRoot); + label4.setLabelFor(myCommitMessage); + label5.setLabelFor(myStrategy); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myPanel; } } diff --git a/plugin/src/main/java/git4idea/merge/GitMergeProvider.java b/plugin/src/main/java/git4idea/merge/GitMergeProvider.java index 295ef40..14cab2e 100644 --- a/plugin/src/main/java/git4idea/merge/GitMergeProvider.java +++ b/plugin/src/main/java/git4idea/merge/GitMergeProvider.java @@ -104,13 +104,13 @@ private static Set findReverseRoots(@Nonnull Project project, @Nonn @Nonnull @Override - public MergeData loadRevisions(final VirtualFile file) throws VcsException { - final MergeData mergeData = new MergeData(); + public MergeData loadRevisions(VirtualFile file) throws VcsException { + MergeData mergeData = new MergeData(); if (file == null) { return mergeData; } - final VirtualFile root = GitUtil.getGitRoot(file); - final FilePath path = VcsUtil.getFilePath(file.getPath()); + VirtualFile root = GitUtil.getGitRoot(file); + FilePath path = VcsUtil.getFilePath(file.getPath()); VcsRunnable runnable = () -> { GitFileRevision original = new GitFileRevision(myProject, path, new GitRevisionNumber(":" + ORIGINAL_REVISION_NUM)); @@ -333,20 +333,13 @@ public void conflictResolvedForFile(VirtualFile file, Resolution resolution) { Conflict c = myConflicts.get(file); assert c != null : "Conflict was not loaded for the file: " + file.getPath(); try { - Conflict.Status status; - switch (resolution) { - case AcceptedTheirs: - status = c.myStatusTheirs; - break; - case AcceptedYours: - status = c.myStatusYours; - break; - case Merged: - status = Conflict.Status.MODIFIED; - break; - default: + Conflict.Status status = switch (resolution) { + case AcceptedTheirs -> c.myStatusTheirs; + case AcceptedYours -> c.myStatusYours; + case Merged -> Conflict.Status.MODIFIED; + default -> throw new IllegalArgumentException("Unsupported resolution for unmergable files(" + file.getPath() + "): " + resolution); - } + }; switch (status) { case MODIFIED: GitFileUtils.addFiles(myProject, c.myRoot, file); @@ -373,7 +366,7 @@ class StatusColumn extends ColumnInfo { private final boolean myIsTheirs; public StatusColumn(boolean isTheirs) { - super(isTheirs ? GitLocalize.mergeToolColumnTheirsStatus().get() : GitLocalize.mergeToolColumnYoursStatus().get()); + super(isTheirs ? GitLocalize.mergeToolColumnTheirsStatus() : GitLocalize.mergeToolColumnYoursStatus()); myIsTheirs = isTheirs; } diff --git a/plugin/src/main/java/git4idea/merge/GitMerger.java b/plugin/src/main/java/git4idea/merge/GitMerger.java index ed1f3ae..836993a 100644 --- a/plugin/src/main/java/git4idea/merge/GitMerger.java +++ b/plugin/src/main/java/git4idea/merge/GitMerger.java @@ -16,7 +16,6 @@ package git4idea.merge; import consulo.project.Project; -import consulo.util.lang.function.Condition; import consulo.versionControlSystem.VcsException; import consulo.versionControlSystem.distributed.repository.Repository; import consulo.virtualFileSystem.VirtualFile; @@ -25,10 +24,9 @@ import git4idea.branch.GitBranchUtil; import git4idea.commands.GitCommand; import git4idea.commands.GitSimpleHandler; -import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; - import jakarta.annotation.Nonnull; + import java.io.File; import java.util.Collection; @@ -36,56 +34,43 @@ import static consulo.util.lang.ObjectUtil.assertNotNull; import static git4idea.GitUtil.getRootsFromRepositories; -public class GitMerger -{ - - private final Project myProject; - private final GitRepositoryManager myRepositoryManager; +public class GitMerger { + private final Project myProject; + private final GitRepositoryManager myRepositoryManager; - public GitMerger(@Nonnull Project project) - { - myProject = project; - myRepositoryManager = GitUtil.getRepositoryManager(myProject); - } + public GitMerger(@Nonnull Project project) { + myProject = project; + myRepositoryManager = GitUtil.getRepositoryManager(myProject); + } - @Nonnull - public Collection getMergingRoots() - { - return getRootsFromRepositories(filter(myRepositoryManager.getRepositories(), new Condition() - { - @Override - public boolean value(GitRepository repository) - { - return repository.getState() == Repository.State.MERGING; - } - })); - } + @Nonnull + public Collection getMergingRoots() { + return getRootsFromRepositories(filter( + myRepositoryManager.getRepositories(), + repository -> repository.getState() == Repository.State.MERGING + )); + } - public void mergeCommit(@Nonnull Collection roots) throws VcsException - { - for(VirtualFile root : roots) - { - mergeCommit(root); - } - } + public void mergeCommit(@Nonnull Collection roots) throws VcsException { + for (VirtualFile root : roots) { + mergeCommit(root); + } + } - public void mergeCommit(@Nonnull VirtualFile root) throws VcsException - { - GitSimpleHandler handler = new GitSimpleHandler(myProject, root, GitCommand.COMMIT); - handler.setStdoutSuppressed(false); + public void mergeCommit(@Nonnull VirtualFile root) throws VcsException { + GitSimpleHandler handler = new GitSimpleHandler(myProject, root, GitCommand.COMMIT); + handler.setStdoutSuppressed(false); - File messageFile = assertNotNull(myRepositoryManager.getRepositoryForRoot(root)).getRepositoryFiles().getMergeMessageFile(); - if(!messageFile.exists()) - { - final GitBranch branch = GitBranchUtil.getCurrentBranch(myProject, root); - final String branchName = branch != null ? branch.getName() : ""; - handler.addParameters("-m", "Merge branch '" + branchName + "' of " + root.getPresentableUrl() + " with conflicts."); - } - else - { - handler.addParameters("-F", messageFile.getAbsolutePath()); - } - handler.endOptions(); - handler.run(); - } + File messageFile = assertNotNull(myRepositoryManager.getRepositoryForRoot(root)).getRepositoryFiles().getMergeMessageFile(); + if (!messageFile.exists()) { + GitBranch branch = GitBranchUtil.getCurrentBranch(myProject, root); + String branchName = branch != null ? branch.getName() : ""; + handler.addParameters("-m", "Merge branch '" + branchName + "' of " + root.getPresentableUrl() + " with conflicts."); + } + else { + handler.addParameters("-F", messageFile.getAbsolutePath()); + } + handler.endOptions(); + handler.run(); + } } diff --git a/plugin/src/main/java/git4idea/merge/GitPullDialog.form b/plugin/src/main/java/git4idea/merge/GitPullDialog.form deleted file mode 100644 index b4ce661..0000000 --- a/plugin/src/main/java/git4idea/merge/GitPullDialog.form +++ /dev/null @@ -1,162 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/merge/GitPullDialog.java b/plugin/src/main/java/git4idea/merge/GitPullDialog.java index 0490979..578724d 100644 --- a/plugin/src/main/java/git4idea/merge/GitPullDialog.java +++ b/plugin/src/main/java/git4idea/merge/GitPullDialog.java @@ -15,6 +15,9 @@ */ package git4idea.merge; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; import consulo.git.localize.GitLocalize; import consulo.localize.LocalizeValue; import consulo.logging.Logger; @@ -22,6 +25,7 @@ import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; import consulo.ui.ex.awt.ElementsChooser; +import consulo.ui.ex.awt.JBUI; import consulo.ui.ex.awt.ListCellRendererWrapper; import consulo.util.lang.StringUtil; import consulo.virtualFileSystem.VirtualFile; @@ -85,7 +89,7 @@ public class GitPullDialog extends DialogWrapper { /** * Selected remote option */ - private JComboBox myRemote; + private JComboBox myRemote; /** * The branch chooser */ @@ -105,6 +109,7 @@ public class GitPullDialog extends DialogWrapper { */ public GitPullDialog(Project project, List roots, VirtualFile defaultRoot) { super(project, true); + $$$setupUI$$$(); setTitle(GitLocalize.pullTitle()); myProject = project; myRepositoryManager = GitUtil.getRepositoryManager(myProject); @@ -114,7 +119,7 @@ public GitPullDialog(Project project, List roots, VirtualFile defau updateRemotes(); updateBranches(); myRemote.addActionListener(e -> updateBranches()); - final ElementsChooser.ElementsMarkListener listener = (element, isMarked) -> validateDialog(); + ElementsChooser.ElementsMarkListener listener = (element, isMarked) -> validateDialog(); myBranchChooser.addElementsMarkListener(listener); listener.elementMarkChanged(null, true); GitUIUtil.imply(mySquashCommitCheckBox, true, myNoCommitCheckBox, true); @@ -162,12 +167,12 @@ public GitLineHandler makeHandler(@Nonnull String url, @Nullable String puttyKey if (myNoFastForwardCheckBox.isSelected()) { h.addParameters("--no-ff"); } - GitMergeStrategy strategy = (GitMergeStrategy)myStrategy.getSelectedItem(); + GitMergeStrategy strategy = (GitMergeStrategy) myStrategy.getSelectedItem(); strategy.addParametersTo(h); h.addParameters("-v"); h.addProgressParameter(); - final List markedBranches = myBranchChooser.getMarkedElements(); + List markedBranches = myBranchChooser.getMarkedElements(); String remote = getRemote(); LOG.assertTrue(remote != null, "Selected remote can't be null here."); // git pull origin master (remote branch name in the format local to that remote) @@ -289,13 +294,13 @@ public ListCellRendererWrapper getGitRemoteListCellRenderer(final Str return new ListCellRendererWrapper<>() { @Override public void customize( - final JList list, - final GitRemote remote, - final int index, - final boolean selected, - final boolean hasFocus + JList list, + GitRemote remote, + int index, + boolean selected, + boolean hasFocus ) { - final LocalizeValue text; + LocalizeValue text; if (remote == null) { text = GitLocalize.utilRemoteRendererNone(); } @@ -317,7 +322,7 @@ else if (defaultRemote != null && defaultRemote.equals(remote.getName())) { * @return a currently selected git root */ public VirtualFile gitRoot() { - return (VirtualFile)myGitRoot.getSelectedItem(); + return (VirtualFile) myGitRoot.getSelectedItem(); } @@ -354,7 +359,7 @@ protected String getHelpId() { @Nullable public String getRemote() { - GitRemote remote = (GitRemote)myRemote.getSelectedItem(); + GitRemote remote = (GitRemote) myRemote.getSelectedItem(); return remote == null ? null : remote.getName(); } @@ -363,4 +368,436 @@ public String getRemote() { public JComponent getPreferredFocusedComponent() { return myBranchChooser.getComponent(); } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + createUIComponents(); + myPanel = new JPanel(); + myPanel.setLayout(new GridLayoutManager(6, 3, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.commonGitRoot().get()); + myPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myGitRoot = new JComboBox(); + myGitRoot.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myPanel.add( + myGitRoot, + new GridConstraints( + 0, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.commonCurrentBranch().get()); + myPanel.add( + label2, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myCurrentBranch = new JLabel(); + myCurrentBranch.setText(" "); + myCurrentBranch.setToolTipText(GitLocalize.commonCurrentBranchTooltip().get()); + myPanel.add( + myCurrentBranch, + new GridConstraints( + 1, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label3 = new JLabel(); + this.$$$loadLabelText$$$(label3, GitLocalize.pullRemote().get()); + myPanel.add( + label3, + new GridConstraints( + 2, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label4 = new JLabel(); + this.$$$loadLabelText$$$(label4, GitLocalize.mergeBranches().get()); + myPanel.add( + label4, + new GridConstraints( + 3, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTHWEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label5 = new JLabel(); + this.$$$loadLabelText$$$(label5, GitLocalize.mergeStrategy().get()); + myPanel.add( + label5, + new GridConstraints( + 4, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + myPanel.add( + spacer1, + new GridConstraints( + 4, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + myStrategy = new JComboBox<>(); + myStrategy.setToolTipText(GitLocalize.mergeStrategy().get()); + myPanel.add( + myStrategy, + new GridConstraints( + 4, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(2, 3, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel1, + new GridConstraints( + 5, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myNoCommitCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myNoCommitCheckBox, GitLocalize.mergeNoCommit().get()); + myNoCommitCheckBox.setToolTipText(GitLocalize.mergeNoCommitTooltip().get()); + panel1.add( + myNoCommitCheckBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + mySquashCommitCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(mySquashCommitCheckBox, GitLocalize.mergeSquashCommit().get()); + mySquashCommitCheckBox.setToolTipText(GitLocalize.mergeSquashTooltip().get()); + panel1.add( + mySquashCommitCheckBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myNoFastForwardCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myNoFastForwardCheckBox, GitLocalize.mergeNoFastForward().get()); + myNoFastForwardCheckBox.setToolTipText(GitLocalize.mergeNoFastForwardTooltip().get()); + panel1.add( + myNoFastForwardCheckBox, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myAddLogInformationCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myAddLogInformationCheckBox, GitLocalize.mergeAddLogInformation().get()); + myAddLogInformationCheckBox.setToolTipText(GitLocalize.mergeAddLogInformationTooltip().get()); + panel1.add( + myAddLogInformationCheckBox, + new GridConstraints( + 1, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer2 = new Spacer(); + panel1.add( + spacer2, + new GridConstraints( + 1, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 1, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel2, + new GridConstraints( + 2, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myRemote = new JComboBox<>(); + myRemote.setEditable(false); + myRemote.setToolTipText(GitLocalize.pullRemoteTooltip().get()); + panel2.add( + myRemote, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myPanel.add( + myBranchChooser, + new GridConstraints( + 3, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null, + 0, + false + ) + ); + label1.setLabelFor(myGitRoot); + label3.setLabelFor(myRemote); + label5.setLabelFor(myStrategy); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myPanel; + } } diff --git a/plugin/src/main/java/git4idea/push/GitDefineRemoteDialog.java b/plugin/src/main/java/git4idea/push/GitDefineRemoteDialog.java index 1d2ef01..3aba77a 100644 --- a/plugin/src/main/java/git4idea/push/GitDefineRemoteDialog.java +++ b/plugin/src/main/java/git4idea/push/GitDefineRemoteDialog.java @@ -16,9 +16,9 @@ package git4idea.push; import consulo.application.progress.ProgressManager; -import consulo.application.util.function.ThrowableComputable; import consulo.component.ProcessCanceledException; -import consulo.logging.Logger; +import consulo.localize.LocalizeValue; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.*; import consulo.util.lang.StringUtil; import consulo.virtualFileSystem.util.VirtualFileUtil; @@ -29,108 +29,112 @@ import git4idea.validators.GitRefNameValidator; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.swing.*; import java.awt.*; -class GitDefineRemoteDialog extends DialogWrapper -{ +class GitDefineRemoteDialog extends DialogWrapper { + private static final Logger LOG = LoggerFactory.getLogger(GitDefineRemoteDialog.class); - private static final Logger LOG = Logger.getInstance(GitDefineRemoteDialog.class); + @Nonnull + private final GitRepository myRepository; + @Nonnull + private final Git myGit; - @Nonnull - private final GitRepository myRepository; - @Nonnull - private final Git myGit; + @Nonnull + private final JTextField myRemoteName; + @Nonnull + private final JTextField myRemoteUrl; - @Nonnull - private final JTextField myRemoteName; - @Nonnull - private final JTextField myRemoteUrl; + GitDefineRemoteDialog(@Nonnull GitRepository repository, @Nonnull Git git) { + super(repository.getProject()); + myRepository = repository; + myGit = git; + myRemoteName = new JTextField(GitRemote.ORIGIN_NAME, 20); + myRemoteUrl = new JTextField(20); + setTitle(LocalizeValue.localizeTODO("Define Remote")); + init(); + } - GitDefineRemoteDialog(@Nonnull GitRepository repository, @Nonnull Git git) - { - super(repository.getProject()); - myRepository = repository; - myGit = git; - myRemoteName = new JTextField(GitRemote.ORIGIN_NAME, 20); - myRemoteUrl = new JTextField(20); - setTitle("Define Remote"); - init(); - } + @Nullable + @Override + protected JComponent createCenterPanel() { + JPanel defineRemoteComponent = new JPanel(new GridBagLayout()); + GridBag gb = new GridBag() + .setDefaultAnchor(GridBagConstraints.LINE_START) + .setDefaultInsets(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, 0, 0); + defineRemoteComponent.add(new JBLabel("Name:"), gb.nextLine().next().anchor(GridBagConstraints.EAST)); + defineRemoteComponent.add(myRemoteName, gb.next()); + defineRemoteComponent.add( + new JBLabel("URL: "), + gb.nextLine().next().anchor(GridBagConstraints.EAST).insets(0, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, 0) + ); + defineRemoteComponent.add(myRemoteUrl, gb.next()); + return defineRemoteComponent; + } - @Nullable - @Override - protected JComponent createCenterPanel() - { - JPanel defineRemoteComponent = new JPanel(new GridBagLayout()); - GridBag gb = new GridBag(). - setDefaultAnchor(GridBagConstraints.LINE_START). - setDefaultInsets(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, 0, 0); - defineRemoteComponent.add(new JBLabel("Name:"), gb.nextLine().next().anchor(GridBagConstraints.EAST)); - defineRemoteComponent.add(myRemoteName, gb.next()); - defineRemoteComponent.add(new JBLabel("URL: "), gb.nextLine().next().anchor(GridBagConstraints.EAST).insets(0, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, 0)); - defineRemoteComponent.add(myRemoteUrl, gb.next()); - return defineRemoteComponent; - } + @Nonnull + String getRemoteName() { + return StringUtil.notNullize(myRemoteName.getText()).trim(); + } - @Nonnull - String getRemoteName() - { - return StringUtil.notNullize(myRemoteName.getText()).trim(); - } + @Nonnull + String getRemoteUrl() { + return StringUtil.notNullize(myRemoteUrl.getText()).trim(); + } - @Nonnull - String getRemoteUrl() - { - return StringUtil.notNullize(myRemoteUrl.getText()).trim(); - } + @Nullable + @Override + @RequiredUIAccess + public JComponent getPreferredFocusedComponent() { + return myRemoteUrl; + } - @Nullable - @Override - public JComponent getPreferredFocusedComponent() - { - return myRemoteUrl; - } + @Override + @RequiredUIAccess + protected void doOKAction() { + LocalizeValue error = validateRemoteUnderModal(getRemoteName(), getRemoteUrl()); + if (error != LocalizeValue.empty()) { + Messages.showErrorDialog(myRepository.getProject(), error.get(), "Invalid Remote"); + } + else { + super.doOKAction(); + } + } - @Override - protected void doOKAction() - { - String name = getRemoteName(); - String url = getRemoteUrl(); - String error = validateRemoteUnderModal(name, url); - if(error != null) - { - LOG.warn(String.format("Invalid remote. Name: [%s], URL: [%s], error: %s", name, url, error)); - Messages.showErrorDialog(myRepository.getProject(), error, "Invalid Remote"); - } - else - { - super.doOKAction(); - } - } - - @Nullable - private String validateRemoteUnderModal(@Nonnull String name, @Nonnull final String url) throws ProcessCanceledException - { - if(url.isEmpty()) - { - return "URL can't be empty"; - } - if(!GitRefNameValidator.getInstance().checkInput(name)) - { - return "Remote name contains illegal characters"; - } - - return ProgressManager.getInstance().runProcessWithProgressSynchronously(new ThrowableComputable() - { - @Override - public String compute() throws ProcessCanceledException - { - final GitCommandResult result = myGit.lsRemote(myRepository.getProject(), VirtualFileUtil.virtualToIoFile(myRepository.getRoot()), url); - return !result.success() ? "Remote URL test failed: " + result.getErrorOutputAsHtmlString() : null; - } - }, "Checking URL...", true, myRepository.getProject()); - } + @Nonnull + private LocalizeValue validateRemoteUnderModal(@Nonnull String name, @Nonnull String url) throws ProcessCanceledException { + if (url.isEmpty()) { + LOG.warn("Invalid remote. Name: {}, URL: {}, error: {}", name, url, "URL can't be empty"); + return LocalizeValue.localizeTODO("URL can't be empty"); + } + if (!GitRefNameValidator.getInstance().checkInput(name)) { + LOG.warn("Invalid remote. Name: {}, URL: {}, error: {}", name, url, "Remote name contains illegal characters"); + return LocalizeValue.localizeTODO("Remote name contains illegal characters"); + } + return ProgressManager.getInstance().runProcessWithProgressSynchronously( + () -> { + GitCommandResult result = + myGit.lsRemote(myRepository.getProject(), VirtualFileUtil.virtualToIoFile(myRepository.getRoot()), url); + if (!result.success()) { + LOG.warn( + "Invalid remote. Name: {}, URL: {}, error: {}", + name, + url, + "Remote URL test failed: " + result.getErrorOutputAsHtmlString() + ); + return LocalizeValue.join(LocalizeValue.localizeTODO("Remote URL test failed: "), result.getErrorOutputAsHtmlValue()); + } + else { + return LocalizeValue.empty(); + } + }, + LocalizeValue.localizeTODO("Checking URL..."), + true, + myRepository.getProject() + ); + } } diff --git a/plugin/src/main/java/git4idea/push/GitOutgoingCommitsProvider.java b/plugin/src/main/java/git4idea/push/GitOutgoingCommitsProvider.java index 65e4f5b..4cc6a63 100644 --- a/plugin/src/main/java/git4idea/push/GitOutgoingCommitsProvider.java +++ b/plugin/src/main/java/git4idea/push/GitOutgoingCommitsProvider.java @@ -15,61 +15,60 @@ */ package git4idea.push; -import java.util.Collections; -import java.util.List; - -import jakarta.annotation.Nonnull; - +import consulo.project.Project; import consulo.versionControlSystem.VcsException; import consulo.versionControlSystem.distributed.push.OutgoingCommitsProvider; import consulo.versionControlSystem.distributed.push.OutgoingResult; import consulo.versionControlSystem.distributed.push.PushSpec; import consulo.versionControlSystem.distributed.push.VcsError; -import consulo.project.Project; import consulo.versionControlSystem.log.VcsFullCommitDetails; import git4idea.GitCommit; import git4idea.GitUtil; import git4idea.history.GitHistoryUtils; import git4idea.repo.GitRepository; +import jakarta.annotation.Nonnull; -public class GitOutgoingCommitsProvider extends OutgoingCommitsProvider -{ +import java.util.Collections; +import java.util.List; - @Nonnull - private final Project myProject; +public class GitOutgoingCommitsProvider extends OutgoingCommitsProvider { + @Nonnull + private final Project myProject; - public GitOutgoingCommitsProvider(@Nonnull Project project) - { - myProject = project; - } + public GitOutgoingCommitsProvider(@Nonnull Project project) { + myProject = project; + } - @Nonnull - @Override - public OutgoingResult getOutgoingCommits(@Nonnull GitRepository repository, - @Nonnull PushSpec pushSpec, - boolean initial) - { - String source = pushSpec.getSource().getBranch().getFullName(); - GitPushTarget target = pushSpec.getTarget(); - String destination = target.getBranch().getFullName(); - try - { - List commits; - if(!target.isNewBranchCreated()) - { - commits = GitHistoryUtils.history(myProject, repository.getRoot(), destination + ".." + source); - } - else - { - commits = GitHistoryUtils.history(myProject, repository.getRoot(), source, "--not", "--remotes=" + target.getBranch().getRemote() - .getName(), "--max-count=" + 1000); - } - return new OutgoingResult(commits, Collections.emptyList()); - } - catch(VcsException e) - { - return new OutgoingResult(Collections.emptyList(), Collections.singletonList(new VcsError(GitUtil - .cleanupErrorPrefixes(e.getMessage())))); - } - } + @Nonnull + @Override + public OutgoingResult getOutgoingCommits( + @Nonnull GitRepository repository, + @Nonnull PushSpec pushSpec, + boolean initial + ) { + String source = pushSpec.getSource().getBranch().getFullName(); + GitPushTarget target = pushSpec.getTarget(); + String destination = target.remoteBranch().getFullName(); + try { + List commits; + if (!target.isNewBranchCreated()) { + commits = GitHistoryUtils.history(myProject, repository.getRoot(), destination + ".." + source); + } + else { + commits = GitHistoryUtils.history( + myProject, + repository.getRoot(), + source, + "--not", + "--remotes=" + target.remoteBranch().getRemote().getName(), + "--max-count=" + 1000 + ); + } + return new OutgoingResult(commits, Collections.emptyList()); + } + catch (VcsException e) { + return new OutgoingResult(Collections.emptyList(), Collections.singletonList(new VcsError(GitUtil + .cleanupErrorPrefixes(e.getMessage())))); + } + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushNativeResult.java b/plugin/src/main/java/git4idea/push/GitPushNativeResult.java index a30fc8a..3b194d2 100644 --- a/plugin/src/main/java/git4idea/push/GitPushNativeResult.java +++ b/plugin/src/main/java/git4idea/push/GitPushNativeResult.java @@ -24,75 +24,64 @@ * @see GitPushNativeResultParser * @see GitPushRepoResult */ -class GitPushNativeResult -{ +class GitPushNativeResult { + static final String NO_FF_REJECT_REASON = "non-fast-forward"; + static final String FETCH_FIRST_REASON = "fetch first"; - static final String NO_FF_REJECT_REASON = "non-fast-forward"; - static final String FETCH_FIRST_REASON = "fetch first"; + enum Type { + SUCCESS, + FORCED_UPDATE, + NEW_REF, + REJECTED, + DELETED, + UP_TO_DATE, + ERROR + } - enum Type - { - SUCCESS, - FORCED_UPDATE, - NEW_REF, - REJECTED, - DELETED, - UP_TO_DATE, - ERROR - } + @Nonnull + private final Type myType; + private final String mySourceRef; + @Nullable + private final String myReason; + @Nullable + private final String myRange; - @Nonnull - private final Type myType; - private final String mySourceRef; - @Nullable - private final String myReason; - @Nullable - private final String myRange; + GitPushNativeResult(@Nonnull Type type, String sourceRef) { + this(type, sourceRef, null, null); + } - GitPushNativeResult(@Nonnull Type type, String sourceRef) - { - this(type, sourceRef, null, null); - } + GitPushNativeResult(@Nonnull Type type, String sourceRef, @Nullable String reason, @Nullable String range) { + myType = type; + mySourceRef = sourceRef; + myReason = reason; + myRange = range; + } - GitPushNativeResult(@Nonnull Type type, String sourceRef, @Nullable String reason, @Nullable String range) - { - myType = type; - mySourceRef = sourceRef; - myReason = reason; - myRange = range; - } + @Nonnull + public Type getType() { + return myType; + } - @Nonnull - public Type getType() - { - return myType; - } + @Nullable + public String getRange() { + return myRange; + } - @Nullable - public String getRange() - { - return myRange; - } + public String getSourceRef() { + return mySourceRef; + } - public String getSourceRef() - { - return mySourceRef; - } + @Nullable + public String getReason() { + return myReason; + } - @Nullable - public String getReason() - { - return myReason; - } + boolean isNonFFUpdate() { + return myType == Type.REJECTED && (NO_FF_REJECT_REASON.equals(myReason) || FETCH_FIRST_REASON.equals(myReason)); + } - boolean isNonFFUpdate() - { - return myType == Type.REJECTED && (NO_FF_REJECT_REASON.equals(myReason) || FETCH_FIRST_REASON.equals(myReason)); - } - - @Override - public String toString() - { - return String.format("%s: '%s', '%s', '%s'", myType, mySourceRef, myRange, myReason); - } + @Override + public String toString() { + return String.format("%s: '%s', '%s', '%s'", myType, mySourceRef, myRange, myReason); + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushOperation.java b/plugin/src/main/java/git4idea/push/GitPushOperation.java index 9bad237..6b456e0 100644 --- a/plugin/src/main/java/git4idea/push/GitPushOperation.java +++ b/plugin/src/main/java/git4idea/push/GitPushOperation.java @@ -179,7 +179,7 @@ else if (pushAttempt == 0 && !mySettings.autoUpdateIfPushRejected()) { } Collection rootsToUpdate = getRootsToUpdate(updateSettings, result.rejected.keySet()); GitUpdateResult updateResult = - update(rootsToUpdate, updateSettings.getUpdateMethod(), rebaseOverMergeProblemDetected == null); + update(rootsToUpdate, updateSettings.updateMethod(), rebaseOverMergeProblemDetected == null); for (GitRepository repository : rootsToUpdate) { updatedRoots.put(repository, updateResult); // TODO update result in GitUpdateProcess is a single for several roots } @@ -221,7 +221,7 @@ private Collection findRootsWithMergeCommits(@Nonnull Collection(source, target); } - String baseRef = pushSpec.getTarget().getBranch().getFullName(); + String baseRef = pushSpec.getTarget().remoteBranch().getFullName(); String currentRef = pushSpec.getSource().getBranch().getFullName(); return GitRebaseOverMergeProblem.hasProblem(myProject, repo.getRoot(), baseRef, currentRef) ? repo.getRoot() : null; }); @@ -291,7 +291,7 @@ private Map push(@Nonnull List GitPushTarget target = spec.getTarget(); GitPushRepoResult repoResult; if (resultWithOutput.isError()) { - repoResult = GitPushRepoResult.error(source, target.getBranch(), resultWithOutput.getErrorAsString()); + repoResult = GitPushRepoResult.error(source, target.remoteBranch(), resultWithOutput.getErrorAsString()); } else { List nativeResults = resultWithOutput.parsedResults; @@ -305,7 +305,7 @@ private Map push(@Nonnull List result -> !result.equals(branchResult) && (result.getType() == NEW_REF || result.getType() == FORCED_UPDATE) ); int commits = collectNumberOfPushedCommits(repository.getRoot(), branchResult); - repoResult = GitPushRepoResult.convertFromNative(branchResult, tagResults, commits, source, target.getBranch()); + repoResult = GitPushRepoResult.convertFromNative(branchResult, tagResults, commits, source, target.remoteBranch()); } LOG.debug("Converted result: " + repoResult); @@ -316,7 +316,7 @@ private Map push(@Nonnull List for (GitRepository repository : repositories) { if (!results.containsKey(repository)) { PushSpec spec = myPushSpecs.get(repository); - results.put(repository, GitPushRepoResult.notPushed(spec.getSource().getBranch(), spec.getTarget().getBranch())); + results.put(repository, GitPushRepoResult.notPushed(spec.getSource().getBranch(), spec.getTarget().remoteBranch())); } } return results; @@ -363,7 +363,7 @@ private void collectUpdatedFiles( private ResultWithOutput doPush(@Nonnull GitRepository repository, @Nonnull PushSpec pushSpec) { GitPushTarget target = pushSpec.getTarget(); GitLocalBranch sourceBranch = pushSpec.getSource().getBranch(); - GitRemoteBranch targetBranch = target.getBranch(); + GitRemoteBranch targetBranch = target.remoteBranch(); GitLineHandlerListener progressListener = GitStandardProgressAnalyzer.createListener(myProgressIndicator); boolean setUpstream = pushSpec.getTarget().isNewBranchCreated() && !branchTrackingInfoIsSet(repository, sourceBranch); @@ -380,10 +380,13 @@ private static boolean branchTrackingInfoIsSet(@Nonnull GitRepository repository } private void savePushUpdateSettings(@Nonnull PushUpdateSettings settings, boolean rebaseOverMergeDetected) { - UpdateMethod updateMethod = settings.getUpdateMethod(); + UpdateMethod updateMethod = settings.updateMethod(); mySettings.setUpdateAllRootsIfPushRejected(settings.shouldUpdateAllRoots()); if (!rebaseOverMergeDetected // don't overwrite explicit "rebase" with temporary "merge" caused by merge commits - && mySettings.getUpdateType() != updateMethod && mySettings.getUpdateType() != UpdateMethod.BRANCH_DEFAULT) { // don't overwrite "branch default" setting + && mySettings.getUpdateType() != updateMethod + // don't overwrite "branch default" setting + && mySettings.getUpdateType() != UpdateMethod.BRANCH_DEFAULT) { + mySettings.setUpdateType(updateMethod); } } diff --git a/plugin/src/main/java/git4idea/push/GitPushOptionsPanel.java b/plugin/src/main/java/git4idea/push/GitPushOptionsPanel.java index 6c7b217..b55ac1d 100644 --- a/plugin/src/main/java/git4idea/push/GitPushOptionsPanel.java +++ b/plugin/src/main/java/git4idea/push/GitPushOptionsPanel.java @@ -15,101 +15,78 @@ */ package git4idea.push; -import java.awt.FlowLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; - -import jakarta.annotation.Nonnull; -import javax.swing.Box; -import javax.swing.JComponent; -import javax.swing.JList; - -import jakarta.annotation.Nullable; - -import consulo.ui.ex.awt.*; -import consulo.versionControlSystem.distributed.push.VcsPushOptionValue; -import consulo.versionControlSystem.distributed.push.VcsPushOptionsPanel; import consulo.ui.ex.awt.ComboBox; import consulo.ui.ex.awt.JBCheckBox; +import consulo.ui.ex.awt.JBUI; +import consulo.ui.ex.awt.ListCellRendererWrapper; +import consulo.versionControlSystem.distributed.push.VcsPushOptionValue; +import consulo.versionControlSystem.distributed.push.VcsPushOptionsPanel; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; -public class GitPushOptionsPanel extends VcsPushOptionsPanel -{ - - @Nonnull - private final JBCheckBox myPushTags; - @Nonnull - private final ComboBox myPushTagsMode; - @Nonnull - private final JBCheckBox myRunHooks; +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyEvent; - public GitPushOptionsPanel(@Nullable GitPushTagMode defaultMode, boolean followTagsSupported, boolean showSkipHookOption) - { - String checkboxText = "Push Tags"; - if(followTagsSupported) - { - checkboxText += ": "; - } - myPushTags = new JBCheckBox(checkboxText); - myPushTags.setMnemonic('T'); - myPushTags.setSelected(defaultMode != null); +public class GitPushOptionsPanel extends VcsPushOptionsPanel { + @Nonnull + private final JBCheckBox myPushTags; + @Nonnull + private final ComboBox myPushTagsMode; + @Nonnull + private final JBCheckBox myRunHooks; - myPushTagsMode = new ComboBox<>(GitPushTagMode.getValues()); - myPushTagsMode.setRenderer(new ListCellRendererWrapper() - { - @Override - public void customize(JList list, GitPushTagMode value, int index, boolean selected, boolean hasFocus) - { - setText(value.getTitle()); - } - }); - myPushTagsMode.setEnabled(myPushTags.isSelected()); - if(defaultMode != null) - { - myPushTagsMode.setSelectedItem(defaultMode); - } + public GitPushOptionsPanel(@Nullable GitPushTagMode defaultMode, boolean followTagsSupported, boolean showSkipHookOption) { + String checkboxText = "Push Tags"; + if (followTagsSupported) { + checkboxText += ": "; + } + myPushTags = new JBCheckBox(checkboxText); + myPushTags.setMnemonic('T'); + myPushTags.setSelected(defaultMode != null); - myPushTags.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(@Nonnull ActionEvent e) - { - myPushTagsMode.setEnabled(myPushTags.isSelected()); - } - }); - myPushTagsMode.setVisible(followTagsSupported); + myPushTagsMode = new ComboBox<>(GitPushTagMode.getValues()); + myPushTagsMode.setRenderer(new ListCellRendererWrapper<>() { + @Override + public void customize(JList list, GitPushTagMode value, int index, boolean selected, boolean hasFocus) { + setText(value.getTitle()); + } + }); + myPushTagsMode.setEnabled(myPushTags.isSelected()); + if (defaultMode != null) { + myPushTagsMode.setSelectedItem(defaultMode); + } - myRunHooks = new JBCheckBox("Run Git hooks"); - myRunHooks.setMnemonic(KeyEvent.VK_H); - myRunHooks.setSelected(true); - myRunHooks.setVisible(showSkipHookOption); + myPushTags.addActionListener(e -> myPushTagsMode.setEnabled(myPushTags.isSelected())); + myPushTagsMode.setVisible(followTagsSupported); - setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); - add(myPushTags); - if(myPushTagsMode.isVisible()) - { - add(Box.createHorizontalStrut(calcStrutWidth(8, myPushTags, myPushTagsMode))); - add(myPushTagsMode); - } - if(myRunHooks.isVisible()) - { - add(Box.createHorizontalStrut(calcStrutWidth(40, myPushTagsMode, myRunHooks))); - add(myRunHooks); - } - } + myRunHooks = new JBCheckBox("Run Git hooks"); + myRunHooks.setMnemonic(KeyEvent.VK_H); + myRunHooks.setSelected(true); + myRunHooks.setVisible(showSkipHookOption); - private static int calcStrutWidth(int plannedWidth, @Nonnull JComponent leftComponent, @Nonnull JComponent rightComponent) - { - return JBUI.scale(plannedWidth) - JBUI.insets(rightComponent.getInsets()).left - JBUI.insets(leftComponent.getInsets()).right; - } + setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); + add(myPushTags); + if (myPushTagsMode.isVisible()) { + add(Box.createHorizontalStrut(calcStrutWidth(8, myPushTags, myPushTagsMode))); + add(myPushTagsMode); + } + if (myRunHooks.isVisible()) { + add(Box.createHorizontalStrut(calcStrutWidth(40, myPushTagsMode, myRunHooks))); + add(myRunHooks); + } + } - @Nullable - @Override - public VcsPushOptionValue getValue() - { - GitPushTagMode selectedTagMode = !myPushTagsMode.isVisible() ? GitPushTagMode.ALL : (GitPushTagMode) myPushTagsMode.getSelectedItem(); - GitPushTagMode tagMode = myPushTags.isSelected() ? selectedTagMode : null; - return new GitVcsPushOptionValue(tagMode, myRunHooks.isVisible() && !myRunHooks.isSelected()); - } + private static int calcStrutWidth(int plannedWidth, @Nonnull JComponent leftComponent, @Nonnull JComponent rightComponent) { + return JBUI.scale(plannedWidth) - JBUI.insets(rightComponent.getInsets()).left - JBUI.insets(leftComponent.getInsets()).right; + } + @Nullable + @Override + public VcsPushOptionValue getValue() { + GitPushTagMode selectedTagMode = + !myPushTagsMode.isVisible() ? GitPushTagMode.ALL : (GitPushTagMode) myPushTagsMode.getSelectedItem(); + GitPushTagMode tagMode = myPushTags.isSelected() ? selectedTagMode : null; + return new GitVcsPushOptionValue(tagMode, myRunHooks.isVisible() && !myRunHooks.isSelected()); + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushRepoResult.java b/plugin/src/main/java/git4idea/push/GitPushRepoResult.java index 9bf1e07..4f5621f 100644 --- a/plugin/src/main/java/git4idea/push/GitPushRepoResult.java +++ b/plugin/src/main/java/git4idea/push/GitPushRepoResult.java @@ -19,9 +19,9 @@ import git4idea.GitLocalBranch; import git4idea.GitRemoteBranch; import git4idea.update.GitUpdateResult; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; + import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -34,174 +34,179 @@ * * @see GitPushNativeResult */ -class GitPushRepoResult -{ - enum Type - { - SUCCESS, - NEW_BRANCH, - UP_TO_DATE, - FORCED, - REJECTED_NO_FF, - REJECTED_OTHER, - ERROR, - NOT_PUSHED; - } - - static Comparator TYPE_COMPARATOR = new Comparator() - { - @Override - public int compare(Type o1, Type o2) - { - return o1.ordinal() - o2.ordinal(); - } - }; - - @Nonnull - private final Type myType; - private final int myCommits; - @Nonnull - private final String mySourceBranch; - @Nonnull - private final String myTargetBranch; - @Nonnull - private final String myTargetRemote; - @Nonnull - private final List myPushedTags; - @Nullable - private final String myError; - @Nullable - private final GitUpdateResult myUpdateResult; - - @Nonnull - static GitPushRepoResult convertFromNative(@Nonnull GitPushNativeResult result, - @Nonnull List tagResults, - int commits, - @Nonnull GitLocalBranch source, - @Nonnull GitRemoteBranch target) - { - List tags = ContainerUtil.map(tagResults, result1 -> result1.getSourceRef()); - return new GitPushRepoResult(convertType(result), commits, source.getFullName(), target.getFullName(), target.getRemote().getName(), tags, null, null); - } - - @Nonnull - static GitPushRepoResult error(@Nonnull GitLocalBranch source, @Nonnull GitRemoteBranch target, @Nonnull String error) - { - return new GitPushRepoResult(Type.ERROR, -1, source.getFullName(), target.getFullName(), target.getRemote().getName(), Collections.emptyList(), error, null); - } - - @Nonnull - static GitPushRepoResult notPushed(GitLocalBranch source, GitRemoteBranch target) - { - return new GitPushRepoResult(Type.NOT_PUSHED, -1, source.getFullName(), target.getFullName(), target.getRemote().getName(), Collections.emptyList(), null, null); - } - - @Nonnull - static GitPushRepoResult addUpdateResult(GitPushRepoResult original, GitUpdateResult updateResult) - { - return new GitPushRepoResult(original.getType(), original.getNumberOfPushedCommits(), original.getSourceBranch(), original.getTargetBranch(), original.getTargetRemote(), - original.getPushedTags(), original.getError(), updateResult); - } - - private GitPushRepoResult(@Nonnull Type type, - int pushedCommits, - @Nonnull String sourceBranch, - @Nonnull String targetBranch, - @Nonnull String targetRemote, - @Nonnull List pushedTags, - @Nullable String error, - @Nullable GitUpdateResult result) - { - myType = type; - myCommits = pushedCommits; - mySourceBranch = sourceBranch; - myTargetBranch = targetBranch; - myTargetRemote = targetRemote; - myPushedTags = pushedTags; - myError = error; - myUpdateResult = result; - } - - @Nonnull - Type getType() - { - return myType; - } - - @Nullable - GitUpdateResult getUpdateResult() - { - return myUpdateResult; - } - - int getNumberOfPushedCommits() - { - return myCommits; - } - - /** - * Returns the branch we were pushing from, in the full-name format, e.g. {@code refs/heads/master}. - */ - @Nonnull - String getSourceBranch() - { - return mySourceBranch; - } - - /** - * Returns the branch we were pushing to, in the full-name format, e.g. {@code refs/remotes/origin/master}. - */ - @Nonnull - String getTargetBranch() - { - return myTargetBranch; - } - - @Nullable - String getError() - { - return myError; - } - - @Nonnull - List getPushedTags() - { - return myPushedTags; - } - - @Nonnull - public String getTargetRemote() - { - return myTargetRemote; - } - - @Nonnull - private static Type convertType(@Nonnull GitPushNativeResult nativeResult) - { - switch(nativeResult.getType()) - { - case SUCCESS: - return Type.SUCCESS; - case FORCED_UPDATE: - return Type.FORCED; - case NEW_REF: - return Type.NEW_BRANCH; - case REJECTED: - return nativeResult.isNonFFUpdate() ? Type.REJECTED_NO_FF : Type.REJECTED_OTHER; - case UP_TO_DATE: - return Type.UP_TO_DATE; - case ERROR: - return Type.ERROR; - case DELETED: - default: - throw new IllegalArgumentException("Conversion is not supported: " + nativeResult.getType()); - } - } - - @Override - public String toString() - { - return String.format("%s (%d, '%s'), update: %s}", myType, myCommits, mySourceBranch, myUpdateResult); - } - +class GitPushRepoResult { + enum Type { + SUCCESS, + NEW_BRANCH, + UP_TO_DATE, + FORCED, + REJECTED_NO_FF, + REJECTED_OTHER, + ERROR, + NOT_PUSHED + } + + static Comparator TYPE_COMPARATOR = (o1, o2) -> o1.ordinal() - o2.ordinal(); + + @Nonnull + private final Type myType; + private final int myCommits; + @Nonnull + private final String mySourceBranch; + @Nonnull + private final String myTargetBranch; + @Nonnull + private final String myTargetRemote; + @Nonnull + private final List myPushedTags; + @Nullable + private final String myError; + @Nullable + private final GitUpdateResult myUpdateResult; + + @Nonnull + static GitPushRepoResult convertFromNative( + @Nonnull GitPushNativeResult result, + @Nonnull List tagResults, + int commits, + @Nonnull GitLocalBranch source, + @Nonnull GitRemoteBranch target + ) { + List tags = ContainerUtil.map(tagResults, GitPushNativeResult::getSourceRef); + return new GitPushRepoResult( + convertType(result), + commits, + source.getFullName(), + target.getFullName(), + target.getRemote().getName(), + tags, + null, + null + ); + } + + @Nonnull + static GitPushRepoResult error(@Nonnull GitLocalBranch source, @Nonnull GitRemoteBranch target, @Nonnull String error) { + return new GitPushRepoResult( + Type.ERROR, + -1, + source.getFullName(), + target.getFullName(), + target.getRemote().getName(), + Collections.emptyList(), + error, + null + ); + } + + @Nonnull + static GitPushRepoResult notPushed(GitLocalBranch source, GitRemoteBranch target) { + return new GitPushRepoResult( + Type.NOT_PUSHED, + -1, + source.getFullName(), + target.getFullName(), + target.getRemote().getName(), + Collections.emptyList(), + null, + null + ); + } + + @Nonnull + static GitPushRepoResult addUpdateResult(GitPushRepoResult original, GitUpdateResult updateResult) { + return new GitPushRepoResult( + original.getType(), + original.getNumberOfPushedCommits(), + original.getSourceBranch(), + original.getTargetBranch(), + original.getTargetRemote(), + original.getPushedTags(), + original.getError(), + updateResult + ); + } + + private GitPushRepoResult( + @Nonnull Type type, + int pushedCommits, + @Nonnull String sourceBranch, + @Nonnull String targetBranch, + @Nonnull String targetRemote, + @Nonnull List pushedTags, + @Nullable String error, + @Nullable GitUpdateResult result + ) { + myType = type; + myCommits = pushedCommits; + mySourceBranch = sourceBranch; + myTargetBranch = targetBranch; + myTargetRemote = targetRemote; + myPushedTags = pushedTags; + myError = error; + myUpdateResult = result; + } + + @Nonnull + Type getType() { + return myType; + } + + @Nullable + GitUpdateResult getUpdateResult() { + return myUpdateResult; + } + + int getNumberOfPushedCommits() { + return myCommits; + } + + /** + * Returns the branch we were pushing from, in the full-name format, e.g. {@code refs/heads/master}. + */ + @Nonnull + String getSourceBranch() { + return mySourceBranch; + } + + /** + * Returns the branch we were pushing to, in the full-name format, e.g. {@code refs/remotes/origin/master}. + */ + @Nonnull + String getTargetBranch() { + return myTargetBranch; + } + + @Nullable + String getError() { + return myError; + } + + @Nonnull + List getPushedTags() { + return myPushedTags; + } + + @Nonnull + public String getTargetRemote() { + return myTargetRemote; + } + + @Nonnull + private static Type convertType(@Nonnull GitPushNativeResult nativeResult) { + return switch (nativeResult.getType()) { + case SUCCESS -> Type.SUCCESS; + case FORCED_UPDATE -> Type.FORCED; + case NEW_REF -> Type.NEW_BRANCH; + case REJECTED -> nativeResult.isNonFFUpdate() ? Type.REJECTED_NO_FF : Type.REJECTED_OTHER; + case UP_TO_DATE -> Type.UP_TO_DATE; + case ERROR -> Type.ERROR; + default -> throw new IllegalArgumentException("Conversion is not supported: " + nativeResult.getType()); + }; + } + + @Override + public String toString() { + return String.format("%s (%d, '%s'), update: %s}", myType, myCommits, mySourceBranch, myUpdateResult); + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushResult.java b/plugin/src/main/java/git4idea/push/GitPushResult.java index 2046f60..1343ae0 100644 --- a/plugin/src/main/java/git4idea/push/GitPushResult.java +++ b/plugin/src/main/java/git4idea/push/GitPushResult.java @@ -18,51 +18,53 @@ import consulo.localHistory.Label; import consulo.versionControlSystem.update.UpdatedFiles; import git4idea.repo.GitRepository; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; + import java.util.Map; /** * Combined push result for all affected repositories in the project. */ class GitPushResult { - @Nonnull - private final Map myResults; - @Nonnull - private final UpdatedFiles myUpdatedFiles; - @Nullable - private final Label myBeforeUpdateLabel; - @Nullable - private final Label myAfterUpdateLabel; + @Nonnull + private final Map myResults; + @Nonnull + private final UpdatedFiles myUpdatedFiles; + @Nullable + private final Label myBeforeUpdateLabel; + @Nullable + private final Label myAfterUpdateLabel; - GitPushResult(@Nonnull Map results, - @Nonnull UpdatedFiles files, - @Nullable Label beforeUpdateLabel, - @Nullable Label afterUpdateLabel) { - myResults = results; - myUpdatedFiles = files; - myBeforeUpdateLabel = beforeUpdateLabel; - myAfterUpdateLabel = afterUpdateLabel; - } + GitPushResult( + @Nonnull Map results, + @Nonnull UpdatedFiles files, + @Nullable Label beforeUpdateLabel, + @Nullable Label afterUpdateLabel + ) { + myResults = results; + myUpdatedFiles = files; + myBeforeUpdateLabel = beforeUpdateLabel; + myAfterUpdateLabel = afterUpdateLabel; + } - @Nonnull - public Map getResults() { - return myResults; - } + @Nonnull + public Map getResults() { + return myResults; + } - @Nonnull - public UpdatedFiles getUpdatedFiles() { - return myUpdatedFiles; - } + @Nonnull + public UpdatedFiles getUpdatedFiles() { + return myUpdatedFiles; + } - @Nullable - public Label getBeforeUpdateLabel() { - return myBeforeUpdateLabel; - } + @Nullable + public Label getBeforeUpdateLabel() { + return myBeforeUpdateLabel; + } - @Nullable - public Label getAfterUpdateLabel() { - return myAfterUpdateLabel; - } + @Nullable + public Label getAfterUpdateLabel() { + return myAfterUpdateLabel; + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushSource.java b/plugin/src/main/java/git4idea/push/GitPushSource.java index 120f7de..6831b47 100644 --- a/plugin/src/main/java/git4idea/push/GitPushSource.java +++ b/plugin/src/main/java/git4idea/push/GitPushSource.java @@ -18,63 +18,61 @@ import consulo.versionControlSystem.distributed.DvcsUtil; import consulo.versionControlSystem.distributed.push.PushSource; import git4idea.GitLocalBranch; - import jakarta.annotation.Nonnull; abstract class GitPushSource implements PushSource { - - @Nonnull - static GitPushSource create(@Nonnull GitLocalBranch branch) { - return new OnBranch(branch); - } - - @Nonnull - static GitPushSource create(@Nonnull String revision) { - return new DetachedHead(revision); - } - - @Nonnull - abstract GitLocalBranch getBranch(); - - private static class OnBranch extends GitPushSource { @Nonnull - private final GitLocalBranch myBranch; - - private OnBranch(@Nonnull GitLocalBranch branch) { - myBranch = branch; + static GitPushSource create(@Nonnull GitLocalBranch branch) { + return new OnBranch(branch); } @Nonnull - @Override - public String getPresentation() { - return myBranch.getName(); + static GitPushSource create(@Nonnull String revision) { + return new DetachedHead(revision); } @Nonnull - @Override - GitLocalBranch getBranch() { - return myBranch; - } - } + abstract GitLocalBranch getBranch(); - private static class DetachedHead extends GitPushSource { - @Nonnull - private final String myRevision; + private static class OnBranch extends GitPushSource { + @Nonnull + private final GitLocalBranch myBranch; - public DetachedHead(@Nonnull String revision) { - myRevision = revision; - } + private OnBranch(@Nonnull GitLocalBranch branch) { + myBranch = branch; + } - @Nonnull - @Override - public String getPresentation() { - return DvcsUtil.getShortHash(myRevision); + @Nonnull + @Override + public String getPresentation() { + return myBranch.getName(); + } + + @Nonnull + @Override + GitLocalBranch getBranch() { + return myBranch; + } } - @Nonnull - @Override - GitLocalBranch getBranch() { - throw new IllegalStateException("Push is not allowed from detached HEAD"); + private static class DetachedHead extends GitPushSource { + @Nonnull + private final String myRevision; + + public DetachedHead(@Nonnull String revision) { + myRevision = revision; + } + + @Nonnull + @Override + public String getPresentation() { + return DvcsUtil.getShortHash(myRevision); + } + + @Nonnull + @Override + GitLocalBranch getBranch() { + throw new IllegalStateException("Push is not allowed from detached HEAD"); + } } - } } diff --git a/plugin/src/main/java/git4idea/push/GitPushSpecParser.java b/plugin/src/main/java/git4idea/push/GitPushSpecParser.java index a6108e2..0c47450 100644 --- a/plugin/src/main/java/git4idea/push/GitPushSpecParser.java +++ b/plugin/src/main/java/git4idea/push/GitPushSpecParser.java @@ -15,79 +15,70 @@ */ package git4idea.push; -import java.util.List; - -import jakarta.annotation.Nonnull; import consulo.logging.Logger; import consulo.util.lang.StringUtil; import git4idea.GitUtil; import git4idea.branch.GitBranchUtil; import git4idea.repo.GitRepository; +import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -class GitPushSpecParser -{ - private static final Logger LOG = Logger.getInstance(GitPushSpecParser.class); +import java.util.List; + +class GitPushSpecParser { + private static final Logger LOG = Logger.getInstance(GitPushSpecParser.class); - @Nullable - static String getTargetRef(@Nonnull GitRepository repository, @Nonnull String sourceBranchName, @Nonnull List specs) - { - // pushing to several pushSpecs is not supported => looking for the first one which is valid & matches the current branch - for(String spec : specs) - { - String target = getTarget(spec, sourceBranchName); - if(target == null) - { - LOG.info("Push spec [" + spec + "] in " + repository.getRoot() + " is invalid or doesn't match source branch " + sourceBranchName); - } - else - { - return target; - } - } - return null; - } + @Nullable + static String getTargetRef(@Nonnull GitRepository repository, @Nonnull String sourceBranchName, @Nonnull List specs) { + // pushing to several pushSpecs is not supported => looking for the first one which is valid & matches the current branch + for (String spec : specs) { + String target = getTarget(spec, sourceBranchName); + if (target == null) { + LOG.info( + "Push spec [" + spec + "] in " + repository.getRoot() + + " is invalid or doesn't match source branch " + sourceBranchName + ); + } + else { + return target; + } + } + return null; + } - @Nullable - private static String getTarget(@Nonnull String spec, @Nonnull String sourceBranch) - { - String[] parts = spec.split(":"); - if(parts.length != 2) - { - return null; - } - String source = parts[0].trim(); - String target = parts[1].trim(); - source = StringUtil.trimStart(source, "+"); + @Nullable + private static String getTarget(@Nonnull String spec, @Nonnull String sourceBranch) { + String[] parts = spec.split(":"); + if (parts.length != 2) { + return null; + } + String source = parts[0].trim(); + String target = parts[1].trim(); + source = StringUtil.trimStart(source, "+"); - if(!isStarPositionValid(source, target)) - { - return null; - } + if (!isStarPositionValid(source, target)) { + return null; + } - source = GitBranchUtil.stripRefsPrefix(source); - sourceBranch = GitBranchUtil.stripRefsPrefix(sourceBranch); - if(source.equals(GitUtil.HEAD) || source.equals(sourceBranch)) - { - return target; - } + source = GitBranchUtil.stripRefsPrefix(source); + sourceBranch = GitBranchUtil.stripRefsPrefix(sourceBranch); + if (source.equals(GitUtil.HEAD) || source.equals(sourceBranch)) { + return target; + } - if(source.endsWith("*")) - { - String sourceWoStar = source.substring(0, source.length() - 1); - if(sourceBranch.startsWith(sourceWoStar)) - { - String starMeaning = sourceBranch.substring(sourceWoStar.length()); - return target.replace("*", starMeaning); - } - } - return null; - } + if (source.endsWith("*")) { + String sourceWoStar = source.substring(0, source.length() - 1); + if (sourceBranch.startsWith(sourceWoStar)) { + String starMeaning = sourceBranch.substring(sourceWoStar.length()); + return target.replace("*", starMeaning); + } + } + return null; + } - private static boolean isStarPositionValid(@Nonnull String source, @Nonnull String target) - { - int sourceStar = source.indexOf('*'); - int targetStar = target.indexOf('*'); - return (sourceStar < 0 && targetStar < 0) || (sourceStar == source.length() - 1 && targetStar == target.length() - 1); - } + private static boolean isStarPositionValid(@Nonnull String source, @Nonnull String target) { + int sourceStar = source.indexOf('*'); + int targetStar = target.indexOf('*'); + return (sourceStar < 0 && targetStar < 0) || (sourceStar == source.length() - 1 && targetStar == target.length() - 1); + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushSupport.java b/plugin/src/main/java/git4idea/push/GitPushSupport.java index 21335a8..d4f1130 100644 --- a/plugin/src/main/java/git4idea/push/GitPushSupport.java +++ b/plugin/src/main/java/git4idea/push/GitPushSupport.java @@ -17,6 +17,7 @@ import consulo.annotation.component.ExtensionImpl; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.lang.ObjectUtil; import consulo.versionControlSystem.AbstractVcs; import consulo.versionControlSystem.distributed.push.*; @@ -146,7 +147,10 @@ private static GitPushTarget makeTargetForNewBranch( @Override public GitPushSource getSource(@Nonnull GitRepository repository) { GitLocalBranch currentBranch = repository.getCurrentBranch(); - return currentBranch != null ? GitPushSource.create(currentBranch) : GitPushSource.create(ObjectUtil.assertNotNull(repository.getCurrentRevision())); // fresh repository is on branch + return currentBranch != null + ? GitPushSource.create(currentBranch) + // fresh repository is on branch + : GitPushSource.create(ObjectUtil.assertNotNull(repository.getCurrentRevision())); } @Nonnull @@ -157,13 +161,14 @@ public RepositoryManager getRepositoryManager() { @Nonnull @Override + @RequiredUIAccess public PushTargetPanel createTargetPanel(@Nonnull GitRepository repository, @Nullable GitPushTarget defaultTarget) { return new GitPushTargetPanel(this, repository, defaultTarget); } @Override public boolean isForcePushAllowed(@Nonnull GitRepository repo, @Nonnull GitPushTarget target) { - final String targetBranch = target.getBranch().getNameForRemoteOperations(); + String targetBranch = target.remoteBranch().getNameForRemoteOperations(); return !mySharedSettings.isBranchProtected(targetBranch); } @@ -187,20 +192,23 @@ private boolean shouldShowSkipHookOption() { && getRepositoryManager().getRepositories() .stream() .map(e -> e.getInfo().hooksInfo()) - .anyMatch(GitHooksInfo::prePushHookAvailable); + .anyMatch(GitHooksInfo::isPrePushHookAvailable); } @Override public boolean isSilentForcePushAllowed(@Nonnull GitPushTarget target) { return myCommonPushSettings.containsForcePushTarget( - target.getBranch().getRemote().getName(), - target.getBranch().getNameForRemoteOperations() + target.remoteBranch().getRemote().getName(), + target.remoteBranch().getNameForRemoteOperations() ); } @Override public void saveSilentForcePushTarget(@Nonnull GitPushTarget target) { - myCommonPushSettings.addForcePushTarget(target.getBranch().getRemote().getName(), target.getBranch().getNameForRemoteOperations()); + myCommonPushSettings.addForcePushTarget( + target.remoteBranch().getRemote().getName(), + target.remoteBranch().getNameForRemoteOperations() + ); } @Override diff --git a/plugin/src/main/java/git4idea/push/GitPushTagMode.java b/plugin/src/main/java/git4idea/push/GitPushTagMode.java index b09a655..a1b5da1 100644 --- a/plugin/src/main/java/git4idea/push/GitPushTagMode.java +++ b/plugin/src/main/java/git4idea/push/GitPushTagMode.java @@ -18,85 +18,69 @@ import consulo.versionControlSystem.distributed.push.VcsPushOptionValue; import jakarta.annotation.Nonnull; -/** - * - */ public final class GitPushTagMode implements VcsPushOptionValue { + public static final GitPushTagMode ALL = new GitPushTagMode("All", "--tags"); + public static final GitPushTagMode FOLLOW = new GitPushTagMode("Current Branch", "--follow-tags"); + + @Nonnull + private String myTitle; + @Nonnull + private String myArgument; + + // for deserialization + @SuppressWarnings("UnusedDeclaration") + public GitPushTagMode() { + this(ALL.getTitle(), ALL.getArgument()); + } - public static final GitPushTagMode ALL = new GitPushTagMode("All", "--tags"); - public static final GitPushTagMode FOLLOW = new GitPushTagMode("Current Branch", "--follow-tags"); - - @Nonnull - private String myTitle; - @Nonnull - private String myArgument; - - // for deserialization - @SuppressWarnings("UnusedDeclaration") - public GitPushTagMode() { - this(ALL.getTitle(), ALL.getArgument()); - } - - private GitPushTagMode(@Nonnull String title, @Nonnull String argument) { - myTitle = title; - myArgument = argument; - } - - @Nonnull - public static GitPushTagMode[] getValues() { - return new GitPushTagMode[]{ - ALL, - FOLLOW - }; - } - - @Nonnull - public String getTitle() { - return myTitle; - } - - @Nonnull - public String getArgument() { - return myArgument; - } - - // for deserialization - @SuppressWarnings("UnusedDeclaration") - public void setTitle(@Nonnull String title) { - myTitle = title; - } - - // for deserialization - @SuppressWarnings("UnusedDeclaration") - public void setArgument(@Nonnull String argument) { - myArgument = argument; - } + private GitPushTagMode(@Nonnull String title, @Nonnull String argument) { + myTitle = title; + myArgument = argument; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + @Nonnull + public static GitPushTagMode[] getValues() { + return new GitPushTagMode[]{ + ALL, + FOLLOW + }; } - if (o == null || getClass() != o.getClass()) { - return false; + + @Nonnull + public String getTitle() { + return myTitle; } - GitPushTagMode mode = (GitPushTagMode)o; + @Nonnull + public String getArgument() { + return myArgument; + } - if (!myArgument.equals(mode.myArgument)) { - return false; + // for deserialization + @SuppressWarnings("UnusedDeclaration") + public void setTitle(@Nonnull String title) { + myTitle = title; } - if (!myTitle.equals(mode.myTitle)) { - return false; + + // for deserialization + @SuppressWarnings("UnusedDeclaration") + public void setArgument(@Nonnull String argument) { + myArgument = argument; } - return true; - } + @Override + public boolean equals(Object o) { + //noinspection SimplifiableIfStatement + if (this == o) { + return true; + } + return o instanceof GitPushTagMode that + && myArgument.equals(that.myArgument) + && myTitle.equals(that.myTitle); + } - @Override - public int hashCode() { - int result = myTitle.hashCode(); - result = 31 * result + myArgument.hashCode(); - return result; - } + @Override + public int hashCode() { + return myArgument.hashCode() + 31 * myTitle.hashCode(); + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushTagPanel.java b/plugin/src/main/java/git4idea/push/GitPushTagPanel.java index 0271fb8..3c8fcf6 100644 --- a/plugin/src/main/java/git4idea/push/GitPushTagPanel.java +++ b/plugin/src/main/java/git4idea/push/GitPushTagPanel.java @@ -15,81 +15,58 @@ */ package git4idea.push; -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JList; - -import jakarta.annotation.Nullable; - +import consulo.ui.ex.awt.ComboBox; import consulo.ui.ex.awt.JBCheckBox; import consulo.ui.ex.awt.ListCellRendererWrapper; import consulo.versionControlSystem.distributed.push.VcsPushOptionValue; import consulo.versionControlSystem.distributed.push.VcsPushOptionsPanel; -import consulo.ui.ex.awt.ComboBox; -import jakarta.annotation.Nonnull; - -@Deprecated -public class GitPushTagPanel extends VcsPushOptionsPanel -{ +import jakarta.annotation.Nullable; - private final ComboBox myCombobox; - private final JBCheckBox myCheckBox; +import javax.swing.*; +import java.awt.*; - public GitPushTagPanel(@Nullable GitPushTagMode defaultMode, boolean followTagsSupported) - { - String checkboxText = "Push Tags"; - if(followTagsSupported) - { - checkboxText += ": "; - } - myCheckBox = new JBCheckBox(checkboxText); - myCheckBox.setMnemonic('T'); - myCheckBox.setSelected(defaultMode != null); +@Deprecated +public class GitPushTagPanel extends VcsPushOptionsPanel { + private final ComboBox myCombobox; + private final JBCheckBox myCheckBox; - setLayout(new BorderLayout()); - add(myCheckBox, BorderLayout.WEST); + public GitPushTagPanel(@Nullable GitPushTagMode defaultMode, boolean followTagsSupported) { + String checkboxText = "Push Tags"; + if (followTagsSupported) { + checkboxText += ": "; + } + myCheckBox = new JBCheckBox(checkboxText); + myCheckBox.setMnemonic('T'); + myCheckBox.setSelected(defaultMode != null); - if(followTagsSupported) - { - myCombobox = new ComboBox(GitPushTagMode.getValues()); - myCombobox.setRenderer(new ListCellRendererWrapper() - { - @Override - public void customize(JList list, GitPushTagMode value, int index, boolean selected, boolean hasFocus) - { - setText(value.getTitle()); - } - }); - myCombobox.setEnabled(myCheckBox.isSelected()); - if(defaultMode != null) - { - myCombobox.setSelectedItem(defaultMode); - } + setLayout(new BorderLayout()); + add(myCheckBox, BorderLayout.WEST); - myCheckBox.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(@Nonnull ActionEvent e) - { - myCombobox.setEnabled(myCheckBox.isSelected()); - } - }); - add(myCombobox, BorderLayout.CENTER); - } - else - { - myCombobox = null; - } + if (followTagsSupported) { + myCombobox = new ComboBox<>(GitPushTagMode.getValues()); + myCombobox.setRenderer(new ListCellRendererWrapper<>() { + @Override + public void customize(JList list, GitPushTagMode value, int index, boolean selected, boolean hasFocus) { + setText(value.getTitle()); + } + }); + myCombobox.setEnabled(myCheckBox.isSelected()); + if (defaultMode != null) { + myCombobox.setSelectedItem(defaultMode); + } - } + myCheckBox.addActionListener(e -> myCombobox.setEnabled(myCheckBox.isSelected())); + add(myCombobox, BorderLayout.CENTER); + } + else { + myCombobox = null; + } - @Nullable - @Override - public VcsPushOptionValue getValue() - { - return myCheckBox.isSelected() ? myCombobox == null ? GitPushTagMode.ALL : (VcsPushOptionValue) myCombobox.getSelectedItem() : null; - } + } + @Nullable + @Override + public VcsPushOptionValue getValue() { + return myCheckBox.isSelected() ? myCombobox == null ? GitPushTagMode.ALL : (VcsPushOptionValue) myCombobox.getSelectedItem() : null; + } } diff --git a/plugin/src/main/java/git4idea/push/GitPushTarget.java b/plugin/src/main/java/git4idea/push/GitPushTarget.java index fc1c02e..1286863 100644 --- a/plugin/src/main/java/git4idea/push/GitPushTarget.java +++ b/plugin/src/main/java/git4idea/push/GitPushTarget.java @@ -38,28 +38,20 @@ import static git4idea.GitBranch.REFS_REMOTES_PREFIX; import static git4idea.GitUtil.findRemoteBranch; -public class GitPushTarget implements PushTarget { - +public record GitPushTarget( + @Nonnull GitRemoteBranch remoteBranch, + boolean isNewBranchCreated, + boolean isPushingToSpecialRef +) implements PushTarget { private static final Logger LOG = Logger.getInstance(GitPushTarget.class); - @Nonnull - private final GitRemoteBranch myRemoteBranch; - private final boolean myIsNewBranchCreated; - private final boolean myPushingToSpecialRef; - public GitPushTarget(@Nonnull GitRemoteBranch remoteBranch, boolean isNewBranchCreated) { this(remoteBranch, isNewBranchCreated, false); } - public GitPushTarget(@Nonnull GitRemoteBranch remoteBranch, boolean isNewBranchCreated, boolean isPushingToSpecialRef) { - myRemoteBranch = remoteBranch; - myIsNewBranchCreated = isNewBranchCreated; - myPushingToSpecialRef = isPushingToSpecialRef; - } - @Nonnull public GitRemoteBranch getBranch() { - return myRemoteBranch; + return remoteBranch(); } @Override @@ -70,16 +62,12 @@ public boolean hasSomethingToPush() { @Nonnull @Override public String getPresentation() { - return myPushingToSpecialRef ? myRemoteBranch.getFullName() : myRemoteBranch.getNameForRemoteOperations(); - } - - public boolean isNewBranchCreated() { - return myIsNewBranchCreated; + return isPushingToSpecialRef ? remoteBranch.getFullName() : remoteBranch.getNameForRemoteOperations(); } @TestOnly boolean isSpecialRef() { - return myPushingToSpecialRef; + return isPushingToSpecialRef; } @Nonnull @@ -152,23 +140,8 @@ private static GitRemote getRemoteToPush(@Nonnull GitRepository repository, @Nul return GitUtil.findOrigin(repository.getRemotes()); } - @Override - public boolean equals(Object o) { - return this == o - || o instanceof GitPushTarget target - && myIsNewBranchCreated == target.myIsNewBranchCreated - && myRemoteBranch.equals(target.myRemoteBranch); - } - - @Override - public int hashCode() { - int result = myRemoteBranch.hashCode(); - result = 31 * result + (myIsNewBranchCreated ? 1 : 0); - return result; - } - @Override public String toString() { - return myRemoteBranch.getNameForLocalOperations(); + return remoteBranch.getNameForLocalOperations(); } } diff --git a/plugin/src/main/java/git4idea/push/GitPushTargetPanel.java b/plugin/src/main/java/git4idea/push/GitPushTargetPanel.java index 5cba0d7..54855ce 100644 --- a/plugin/src/main/java/git4idea/push/GitPushTargetPanel.java +++ b/plugin/src/main/java/git4idea/push/GitPushTargetPanel.java @@ -22,6 +22,7 @@ import consulo.document.event.DocumentAdapter; import consulo.document.event.DocumentEvent; import consulo.ide.ServiceManager; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; @@ -40,7 +41,10 @@ import consulo.util.collection.ContainerUtil; import consulo.versionControlSystem.distributed.push.PushTargetEditorListener; import consulo.versionControlSystem.distributed.push.PushTargetPanel; -import consulo.versionControlSystem.distributed.ui.awt.*; +import consulo.versionControlSystem.distributed.ui.awt.PushLogTreeUtil; +import consulo.versionControlSystem.distributed.ui.awt.PushTargetTextField; +import consulo.versionControlSystem.distributed.ui.awt.VcsEditableTextComponent; +import consulo.versionControlSystem.distributed.ui.awt.VcsLinkedTextComponent; import git4idea.GitRemoteBranch; import git4idea.commands.Git; import git4idea.commands.GitCommandResult; @@ -50,9 +54,10 @@ import jakarta.annotation.Nullable; import javax.swing.*; -import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; -import java.awt.event.*; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.HierarchyEvent; import java.text.ParseException; import java.util.Comparator; import java.util.List; @@ -86,6 +91,7 @@ public class GitPushTargetPanel extends PushTargetPanel { @Nullable private Runnable myFireOnChangeAction; + @RequiredUIAccess public GitPushTargetPanel(@Nonnull GitPushSupport support, @Nonnull GitRepository repository, @Nullable GitPushTarget defaultTarget) { myPushSupport = support; myRepository = repository; @@ -94,9 +100,9 @@ public GitPushTargetPanel(@Nonnull GitPushSupport support, @Nonnull GitRepositor myTargetRenderer = new VcsEditableTextComponent("", null); myTargetEditor = new PushTargetTextField(repository.getProject(), getTargetNames(myRepository), ""); - myRemoteRenderer = new VcsLinkedTextComponent("", new VcsLinkListener() { - @Override - public void hyperlinkActivated(@Nonnull DefaultMutableTreeNode sourceNode, @Nonnull MouseEvent event) { + myRemoteRenderer = new VcsLinkedTextComponent( + "", + (sourceNode, event) -> { if (myRepository.getRemotes().isEmpty()) { showDefineRemoteDialog(); } @@ -107,7 +113,7 @@ public void hyperlinkActivated(@Nonnull DefaultMutableTreeNode sourceNode, @Nonn } } } - }); + ); setLayout(new BorderLayout()); setOpaque(false); @@ -139,6 +145,7 @@ public void focusGained(FocusEvent e) { myTargetEditor.getDocument().putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } + @RequiredUIAccess private void updateComponents(@Nullable GitPushTarget target) { myCurrentTarget = target; @@ -158,7 +165,7 @@ else if (!noRemotes) { } else { initialBranch = getTextFieldText(target); - initialRemote = target.getBranch().getRemote().getName(); + initialRemote = target.remoteBranch().getRemote().getName(); } myTargetRenderer.updateLinkText(initialBranch); @@ -168,6 +175,7 @@ else if (!noRemotes) { myTargetEditor.setVisible(!noRemotes); } + @RequiredUIAccess private void showDefineRemoteDialog() { GitDefineRemoteDialog dialog = new GitDefineRemoteDialog(myRepository, myGit); if (dialog.showAndGet()) { @@ -176,7 +184,7 @@ private void showDefineRemoteDialog() { } private void addRemoteUnderModal(@Nonnull final String remoteName, @Nonnull final String remoteUrl) { - ProgressManager.getInstance().run(new Task.Modal(myRepository.getProject(), "Adding remote...", true) { + ProgressManager.getInstance().run(new Task.Modal(myRepository.getProject(), LocalizeValue.localizeTODO("Adding remote..."), true) { private GitCommandResult myResult; @Override @@ -238,9 +246,15 @@ private List getRemotes() { } @Override - public void render(@Nonnull ColoredTreeCellRenderer renderer, boolean isSelected, boolean isActive, @Nullable String forceRenderedText) { - - SimpleTextAttributes targetTextAttributes = PushLogTreeUtil.addTransparencyIfNeeded(SimpleTextAttributes.REGULAR_ATTRIBUTES, isActive); + public void render( + @Nonnull ColoredTreeCellRenderer renderer, + boolean isSelected, + boolean isActive, + @Nullable String forceRenderedText + ) { + + SimpleTextAttributes targetTextAttributes = + PushLogTreeUtil.addTransparencyIfNeeded(SimpleTextAttributes.REGULAR_ATTRIBUTES, isActive); if (myError != null) { renderer.append(myError, PushLogTreeUtil.addTransparencyIfNeeded(SimpleTextAttributes.ERROR_ATTRIBUTES, isActive)); } @@ -264,7 +278,11 @@ public void render(@Nonnull ColoredTreeCellRenderer renderer, boolean isSelected } GitPushTarget target = getValue(); if (target != null && target.isNewBranchCreated()) { - renderer.append("+", PushLogTreeUtil.addTransparencyIfNeeded(SimpleTextAttributes.SYNTHETIC_ATTRIBUTES, isActive), this); + renderer.append( + "+", + PushLogTreeUtil.addTransparencyIfNeeded(SimpleTextAttributes.SYNTHETIC_ATTRIBUTES, isActive), + this + ); } myTargetRenderer.setSelected(isSelected); myTargetRenderer.setTransparent(!isActive); @@ -281,10 +299,11 @@ public GitPushTarget getValue() { @Nonnull private static String getTextFieldText(@Nullable GitPushTarget target) { - return (target != null ? target.getBranch().getNameForRemoteOperations() : ""); + return (target != null ? target.remoteBranch().getNameForRemoteOperations() : ""); } @Override + @RequiredUIAccess public void fireOnCancel() { myTargetEditor.setText(getTextFieldText(myCurrentTarget)); } @@ -330,7 +349,7 @@ public void setFireOnChangeAction(@Nonnull Runnable action) { @Nonnull private static List getTargetNames(@Nonnull GitRepository repository) { List remoteBranches = ContainerUtil.sorted(repository.getBranches().getRemoteBranches(), REMOTE_BRANCH_COMPARATOR); - return ContainerUtil.map(remoteBranches, branch -> branch.getNameForRemoteOperations()); + return ContainerUtil.map(remoteBranches, GitRemoteBranch::getNameForRemoteOperations); } private static class MyRemoteBranchComparator implements Comparator { @@ -366,12 +385,9 @@ public void focusGained(FocusEvent e) { processActiveUserChanges(listener); } }); - myTargetEditor.addHierarchyListener(new HierarchyListener() { - @Override - public void hierarchyChanged(HierarchyEvent e) { - if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) { - myTargetEditor.getDocument().putUserData(UndoConstants.DONT_RECORD_UNDO, !myTargetEditor.isShowing()); - } + myTargetEditor.addHierarchyListener(e -> { + if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) { + myTargetEditor.getDocument().putUserData(UndoConstants.DONT_RECORD_UNDO, !myTargetEditor.isShowing()); } }); } @@ -384,6 +400,7 @@ private void processActiveUserChanges(@Nonnull PushTargetEditorListener listener } @Override + @RequiredUIAccess public void forceUpdateEditableUiModel(@Nonnull String forcedText) { //if targetEditor is now editing by user, it shouldn't be force updated if (!myTargetEditor.isShowing()) { diff --git a/plugin/src/main/java/git4idea/push/GitPusher.java b/plugin/src/main/java/git4idea/push/GitPusher.java index 0bbf74c..b3602e3 100644 --- a/plugin/src/main/java/git4idea/push/GitPusher.java +++ b/plugin/src/main/java/git4idea/push/GitPusher.java @@ -59,7 +59,7 @@ public void push( GitPushTagMode pushTagMode; boolean skipHook; if (optionValue instanceof GitVcsPushOptionValue pushOptionValue) { - pushTagMode = pushOptionValue.getPushTagMode(); + pushTagMode = pushOptionValue.pushTagMode(); skipHook = pushOptionValue.isSkipHook(); } else { @@ -90,12 +90,12 @@ private void rememberTargets(@Nonnull Map myRepositories; - private final boolean myRebaseOverMergeProblemDetected; - private final JCheckBox myUpdateAllRoots; - private final RebaseAction myRebaseAction; - private final MergeAction myMergeAction; - private final JCheckBox myAutoUpdateInFuture; - - protected GitRejectedPushUpdateDialog(@Nonnull Project project, - @Nonnull Collection repositories, - @Nonnull PushUpdateSettings initialSettings, - boolean rebaseOverMergeProblemDetected) { - super(project); - myProject = project; - myRepositories = repositories; - myRebaseOverMergeProblemDetected = rebaseOverMergeProblemDetected; - - myUpdateAllRoots = new JCheckBox("Update not rejected repositories as well", initialSettings.shouldUpdateAllRoots()); - myUpdateAllRoots.setMnemonic('u'); - myAutoUpdateInFuture = - new JCheckBox("Remember the update method choice and silently update in future
(you may change " + - "this" + " in the Settings)"); - myAutoUpdateInFuture.setMnemonic('s'); - - myMergeAction = new MergeAction(); - myRebaseAction = new RebaseAction(); - setDefaultAndFocusedActions(initialSettings.getUpdateMethod()); - init(); - setTitle("Push Rejected"); - } - - private void setDefaultAndFocusedActions(@Nullable UpdateMethod updateMethod) { - Action defaultAction; - Action focusedAction; - if (myRebaseOverMergeProblemDetected) { - defaultAction = myMergeAction; - focusedAction = getCancelAction(); - } - else if (updateMethod == UpdateMethod.REBASE) { - defaultAction = myRebaseAction; - focusedAction = myMergeAction; + static final int MERGE_EXIT_CODE = NEXT_USER_EXIT_CODE; + static final int REBASE_EXIT_CODE = MERGE_EXIT_CODE + 1; + + private static final String HTML_INDENT = "    "; + public static final String DESCRIPTION_START = "Push of current branch "; + + private final Project myProject; + private final Collection myRepositories; + private final boolean myRebaseOverMergeProblemDetected; + private final JCheckBox myUpdateAllRoots; + private final RebaseAction myRebaseAction; + private final MergeAction myMergeAction; + private final JCheckBox myAutoUpdateInFuture; + + protected GitRejectedPushUpdateDialog( + @Nonnull Project project, + @Nonnull Collection repositories, + @Nonnull PushUpdateSettings initialSettings, + boolean rebaseOverMergeProblemDetected + ) { + super(project); + myProject = project; + myRepositories = repositories; + myRebaseOverMergeProblemDetected = rebaseOverMergeProblemDetected; + + myUpdateAllRoots = new JCheckBox("Update not rejected repositories as well", initialSettings.shouldUpdateAllRoots()); + myUpdateAllRoots.setMnemonic('u'); + myAutoUpdateInFuture = new JCheckBox( + "Remember the update method choice and silently update in future
" + + "(you may change this in the Settings)" + ); + myAutoUpdateInFuture.setMnemonic('s'); + + myMergeAction = new MergeAction(); + myRebaseAction = new RebaseAction(); + setDefaultAndFocusedActions(initialSettings.updateMethod()); + init(); + setTitle(LocalizeValue.localizeTODO("Push Rejected")); } - else { - defaultAction = myMergeAction; - focusedAction = myRebaseAction; + + private void setDefaultAndFocusedActions(@Nullable UpdateMethod updateMethod) { + Action defaultAction; + Action focusedAction; + if (myRebaseOverMergeProblemDetected) { + defaultAction = myMergeAction; + focusedAction = getCancelAction(); + } + else if (updateMethod == UpdateMethod.REBASE) { + defaultAction = myRebaseAction; + focusedAction = myMergeAction; + } + else { + defaultAction = myMergeAction; + focusedAction = myRebaseAction; + } + defaultAction.putValue(DEFAULT_ACTION, Boolean.TRUE); + focusedAction.putValue(FOCUSED_ACTION, Boolean.TRUE); } - defaultAction.putValue(DEFAULT_ACTION, Boolean.TRUE); - focusedAction.putValue(FOCUSED_ACTION, Boolean.TRUE); - } - @Override - protected JComponent createCenterPanel() { - JBLabel desc = new JBLabel(wrapInHtml(makeDescription())); + @Override + protected JComponent createCenterPanel() { + JBLabel desc = new JBLabel(wrapInHtml(makeDescription())); + + JPanel options = new JPanel(new BorderLayout()); + if (!myRebaseOverMergeProblemDetected) { + options.add(myAutoUpdateInFuture, BorderLayout.SOUTH); + } + + if (!GitUtil.justOneGitRepository(myProject)) { + options.add(myUpdateAllRoots); + } + + int GAP = 15; + JPanel rootPanel = new JPanel(new BorderLayout(GAP, GAP)); + rootPanel.add(desc); + rootPanel.add(options, BorderLayout.SOUTH); + JLabel iconLabel = new JBLabel(myRebaseOverMergeProblemDetected ? UIUtil.getWarningIcon() : UIUtil.getQuestionIcon()); + rootPanel.add(iconLabel, BorderLayout.WEST); - JPanel options = new JPanel(new BorderLayout()); - if (!myRebaseOverMergeProblemDetected) { - options.add(myAutoUpdateInFuture, BorderLayout.SOUTH); + return rootPanel; } - if (!GitUtil.justOneGitRepository(myProject)) { - options.add(myUpdateAllRoots); + @Override + protected String getHelpId() { + return "reference.VersionControl.Git.UpdateOnRejectedPushDialog"; } - final int GAP = 15; - JPanel rootPanel = new JPanel(new BorderLayout(GAP, GAP)); - rootPanel.add(desc); - rootPanel.add(options, BorderLayout.SOUTH); - JLabel iconLabel = new JBLabel(myRebaseOverMergeProblemDetected ? UIUtil.getWarningIcon() : UIUtil.getQuestionIcon()); - rootPanel.add(iconLabel, BorderLayout.WEST); - - return rootPanel; - } - - @Override - protected String getHelpId() { - return "reference.VersionControl.Git.UpdateOnRejectedPushDialog"; - } - - private String makeDescription() { - if (GitUtil.justOneGitRepository(myProject)) { - assert !myRepositories.isEmpty() : "repositories are empty"; - GitRepository repository = myRepositories.iterator().next(); - GitBranch currentBranch = getCurrentBranch(repository); - return DESCRIPTION_START + code(currentBranch.getName()) + " was rejected.
" + descriptionEnding(); + private String makeDescription() { + if (GitUtil.justOneGitRepository(myProject)) { + assert !myRepositories.isEmpty() : "repositories are empty"; + GitRepository repository = myRepositories.iterator().next(); + GitBranch currentBranch = getCurrentBranch(repository); + return DESCRIPTION_START + code(currentBranch.getName()) + " was rejected.
" + descriptionEnding(); + } + else if (myRepositories.size() == 1) { // there are more than 1 repositories in the project, but only one was rejected + GitRepository repository = myRepositories.iterator().next(); + GitBranch currentBranch = getCurrentBranch(repository); + + return DESCRIPTION_START + code(currentBranch.getName()) + " in repository
" + code(repository.getPresentableUrl()) + + " was rejected.
" + descriptionEnding(); + } + else { // several repositories rejected the push + Map currentBranches = getCurrentBranches(); + if (allBranchesHaveTheSameName(currentBranches)) { + String branchName = currentBranches.values().iterator().next().getName(); + StringBuilder sb = new StringBuilder(DESCRIPTION_START + code(branchName) + " was rejected in repositories
"); + for (GitRepository repository : DvcsUtil.sortRepositories(currentBranches.keySet())) { + sb.append(HTML_INDENT).append(code(repository.getPresentableUrl())).append("
"); + } + sb.append(descriptionEnding()); + return sb.toString(); + } + else { + StringBuilder sb = new StringBuilder("Push of current branch was rejected:
"); + for (Map.Entry entry : currentBranches.entrySet()) { + GitRepository repository = entry.getKey(); + GitBranch currentBranch = entry.getValue(); + sb.append(HTML_INDENT).append(code(currentBranch.getName())) + .append(" in ").append(code(repository.getPresentableUrl())).append("
"); + } + sb.append(descriptionEnding()); + return sb.toString(); + } + } } - else if (myRepositories.size() == 1) { // there are more than 1 repositories in the project, but only one was rejected - GitRepository repository = myRepositories.iterator().next(); - GitBranch currentBranch = getCurrentBranch(repository); - return DESCRIPTION_START + code(currentBranch.getName()) + " in repository
" + code(repository.getPresentableUrl()) + - " was rejected.
" + descriptionEnding(); + @Nonnull + private String descriptionEnding() { + String desc = "Remote changes need to be merged before pushing."; + if (myRebaseOverMergeProblemDetected) { + desc += + "

In this case merge is highly recommended, because there are non-pushed merge commits. " + "
Rebasing them" + + " " + + "can lead to problems."; + } + return desc; } - else { // several repositories rejected the push - Map currentBranches = getCurrentBranches(); - if (allBranchesHaveTheSameName(currentBranches)) { - String branchName = currentBranches.values().iterator().next().getName(); - StringBuilder sb = new StringBuilder(DESCRIPTION_START + code(branchName) + " was rejected in repositories
"); - for (GitRepository repository : DvcsUtil.sortRepositories(currentBranches.keySet())) { - sb.append(HTML_INDENT).append(code(repository.getPresentableUrl())).append("
"); + + private static boolean allBranchesHaveTheSameName(@Nonnull Map branches) { + String name = null; + for (GitBranch branch : branches.values()) { + if (name == null) { + name = branch.getName(); + } + else if (!name.equals(branch.getName())) { + return false; + } } - sb.append(descriptionEnding()); - return sb.toString(); - } - else { - StringBuilder sb = new StringBuilder("Push of current branch was rejected:
"); - for (Map.Entry entry : currentBranches.entrySet()) { - GitRepository repository = entry.getKey(); - GitBranch currentBranch = entry.getValue(); - sb.append(HTML_INDENT).append(code(currentBranch.getName())) - .append(" in ").append(code(repository.getPresentableUrl())).append("
"); + return true; + } + + @Nonnull + private Map getCurrentBranches() { + Map currentBranches = new HashMap<>(); + for (GitRepository repository : myRepositories) { + currentBranches.put(repository, getCurrentBranch(repository)); } - sb.append(descriptionEnding()); - return sb.toString(); - } + return currentBranches; } - } - - @Nonnull - private String descriptionEnding() { - String desc = "Remote changes need to be merged before pushing."; - if (myRebaseOverMergeProblemDetected) { - desc += - "

In this case merge is highly recommended, because there are non-pushed merge commits. " + "
Rebasing them" + - " " + - "can lead to problems."; + + @Nonnull + private static GitBranch getCurrentBranch(GitRepository repository) { + GitBranch currentBranch = repository.getCurrentBranch(); + assert currentBranch != null : "Current branch can't be null here. " + repository; + return currentBranch; } - return desc; - } - - private static boolean allBranchesHaveTheSameName(@Nonnull Map branches) { - String name = null; - for (GitBranch branch : branches.values()) { - if (name == null) { - name = branch.getName(); - } - else if (!name.equals(branch.getName())) { - return false; - } + + @Nonnull + @Override + protected Action[] createActions() { + return new Action[]{ + getCancelAction(), + myMergeAction, + myRebaseAction + }; } - return true; - } - - @Nonnull - private Map getCurrentBranches() { - Map currentBranches = new HashMap(); - for (GitRepository repository : myRepositories) { - currentBranches.put(repository, getCurrentBranch(repository)); + + boolean shouldUpdateAll() { + return myUpdateAllRoots.isSelected(); } - return currentBranches; - } - - @Nonnull - private static GitBranch getCurrentBranch(GitRepository repository) { - GitBranch currentBranch = repository.getCurrentBranch(); - assert currentBranch != null : "Current branch can't be null here. " + repository; - return currentBranch; - } - - @Nonnull - @Override - protected Action[] createActions() { - return new Action[]{ - getCancelAction(), - myMergeAction, - myRebaseAction - }; - } - - boolean shouldUpdateAll() { - return myUpdateAllRoots.isSelected(); - } - - boolean shouldAutoUpdateInFuture() { - return myAutoUpdateInFuture.isSelected(); - } - - @TestOnly - boolean warnsAboutRebaseOverMerge() { - return myRebaseOverMergeProblemDetected; - } - - private class MergeAction extends AbstractAction { - MergeAction() { - super("&Merge"); + + boolean shouldAutoUpdateInFuture() { + return myAutoUpdateInFuture.isSelected(); } - @Override - public void actionPerformed(ActionEvent e) { - close(MERGE_EXIT_CODE); + @TestOnly + boolean warnsAboutRebaseOverMerge() { + return myRebaseOverMergeProblemDetected; } - } - private class RebaseAction extends AbstractAction { + private class MergeAction extends AbstractAction { + MergeAction() { + super("&Merge"); + } - RebaseAction() { - super(myRebaseOverMergeProblemDetected ? "Rebase Anyway" : "&Rebase"); + @Override + public void actionPerformed(ActionEvent e) { + close(MERGE_EXIT_CODE); + } } - @Override - public void actionPerformed(ActionEvent e) { - close(REBASE_EXIT_CODE); + private class RebaseAction extends AbstractAction { + + RebaseAction() { + super(myRebaseOverMergeProblemDetected ? "Rebase Anyway" : "&Rebase"); + } + + @Override + public void actionPerformed(ActionEvent e) { + close(REBASE_EXIT_CODE); + } } - } } diff --git a/plugin/src/main/java/git4idea/push/GitSpecialRefRemoteBranch.java b/plugin/src/main/java/git4idea/push/GitSpecialRefRemoteBranch.java index ea751a1..e487ad6 100644 --- a/plugin/src/main/java/git4idea/push/GitSpecialRefRemoteBranch.java +++ b/plugin/src/main/java/git4idea/push/GitSpecialRefRemoteBranch.java @@ -15,50 +15,44 @@ */ package git4idea.push; -import jakarta.annotation.Nonnull; import git4idea.GitRemoteBranch; import git4idea.repo.GitRemote; +import jakarta.annotation.Nonnull; /** * Semi-fake remote branch if pushing to special push specs like "HEAD:refs/for/master". */ -class GitSpecialRefRemoteBranch extends GitRemoteBranch -{ - private final String myRef; - private final GitRemote myRemote; +class GitSpecialRefRemoteBranch extends GitRemoteBranch { + private final String myRef; + private final GitRemote myRemote; - public GitSpecialRefRemoteBranch(@Nonnull String ref, @Nonnull GitRemote remote) - { - super(ref); - myRef = ref; - myRemote = remote; - } + public GitSpecialRefRemoteBranch(@Nonnull String ref, @Nonnull GitRemote remote) { + super(ref); + myRef = ref; + myRemote = remote; + } - @Nonnull - @Override - public String getNameForRemoteOperations() - { - return myRef; - } + @Nonnull + @Override + public String getNameForRemoteOperations() { + return myRef; + } - @Nonnull - @Override - public String getNameForLocalOperations() - { - return myRef; - } + @Nonnull + @Override + public String getNameForLocalOperations() { + return myRef; + } - @Nonnull - @Override - public GitRemote getRemote() - { - return myRemote; - } + @Nonnull + @Override + public GitRemote getRemote() { + return myRemote; + } - @Nonnull - @Override - public String getFullName() - { - return myRef; - } + @Nonnull + @Override + public String getFullName() { + return myRef; + } } diff --git a/plugin/src/main/java/git4idea/push/GitVcsPushOptionValue.java b/plugin/src/main/java/git4idea/push/GitVcsPushOptionValue.java index ff390a5..07496aa 100644 --- a/plugin/src/main/java/git4idea/push/GitVcsPushOptionValue.java +++ b/plugin/src/main/java/git4idea/push/GitVcsPushOptionValue.java @@ -2,71 +2,9 @@ import consulo.versionControlSystem.distributed.push.VcsPushOptionValue; -/** - * from kotlin - */ -public class GitVcsPushOptionValue implements VcsPushOptionValue -{ - private final GitPushTagMode myPushTagMode; - private final boolean mySkipHook; - - public GitVcsPushOptionValue(GitPushTagMode pushTagMode, boolean skipHook) - { - myPushTagMode = pushTagMode; - mySkipHook = skipHook; - } - - public GitPushTagMode getPushTagMode() - { - return myPushTagMode; - } - - public boolean isSkipHook() - { - return mySkipHook; - } - - @Override - public boolean equals(Object o) - { - if(this == o) - { - return true; - } - if(o == null || getClass() != o.getClass()) - { - return false; - } - - GitVcsPushOptionValue that = (GitVcsPushOptionValue) o; - - if(mySkipHook != that.mySkipHook) - { - return false; - } - if(myPushTagMode != null ? !myPushTagMode.equals(that.myPushTagMode) : that.myPushTagMode != null) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = myPushTagMode != null ? myPushTagMode.hashCode() : 0; - result = 31 * result + (mySkipHook ? 1 : 0); - return result; - } - - @Override - public String toString() - { - final StringBuilder sb = new StringBuilder("GitVcsPushOptionValue{"); - sb.append("myPushTagMode=").append(myPushTagMode); - sb.append(", mySkipHook=").append(mySkipHook); - sb.append('}'); - return sb.toString(); - } +public record GitVcsPushOptionValue(GitPushTagMode pushTagMode, boolean isSkipHook) implements VcsPushOptionValue { + @Deprecated + public GitPushTagMode getPushTagMode() { + return pushTagMode(); + } } diff --git a/plugin/src/main/java/git4idea/push/GroupedPushResult.java b/plugin/src/main/java/git4idea/push/GroupedPushResult.java index c128119..9cec3af 100644 --- a/plugin/src/main/java/git4idea/push/GroupedPushResult.java +++ b/plugin/src/main/java/git4idea/push/GroupedPushResult.java @@ -16,63 +16,56 @@ package git4idea.push; import git4idea.repo.GitRepository; - import jakarta.annotation.Nonnull; + import java.util.HashMap; import java.util.Map; -class GroupedPushResult -{ - - @Nonnull - final Map successful; - @Nonnull - final Map errors; - @Nonnull - final Map rejected; - @Nonnull - final Map customRejected; +class GroupedPushResult { + @Nonnull + final Map successful; + @Nonnull + final Map errors; + @Nonnull + final Map rejected; + @Nonnull + final Map customRejected; - private GroupedPushResult(@Nonnull Map successful, - @Nonnull Map errors, - @Nonnull Map rejected, - @Nonnull Map customRejected) - { - this.successful = successful; - this.errors = errors; - this.rejected = rejected; - this.customRejected = customRejected; - } + private GroupedPushResult( + @Nonnull Map successful, + @Nonnull Map errors, + @Nonnull Map rejected, + @Nonnull Map customRejected + ) { + this.successful = successful; + this.errors = errors; + this.rejected = rejected; + this.customRejected = customRejected; + } - @Nonnull - static GroupedPushResult group(@Nonnull Map results) - { - Map successful = new HashMap<>(); - Map rejected = new HashMap<>(); - Map customRejected = new HashMap<>(); - Map errors = new HashMap<>(); - for(Map.Entry entry : results.entrySet()) - { - GitRepository repository = entry.getKey(); - GitPushRepoResult result = entry.getValue(); + @Nonnull + static GroupedPushResult group(@Nonnull Map results) { + Map successful = new HashMap<>(); + Map rejected = new HashMap<>(); + Map customRejected = new HashMap<>(); + Map errors = new HashMap<>(); + for (Map.Entry entry : results.entrySet()) { + GitRepository repository = entry.getKey(); + GitPushRepoResult result = entry.getValue(); - if(result.getType() == GitPushRepoResult.Type.REJECTED_NO_FF) - { - rejected.put(repository, result); - } - else if(result.getType() == GitPushRepoResult.Type.ERROR) - { - errors.put(repository, result); - } - else if(result.getType() == GitPushRepoResult.Type.REJECTED_OTHER) - { - customRejected.put(repository, result); - } - else - { - successful.put(repository, result); - } - } - return new GroupedPushResult(successful, errors, rejected, customRejected); - } + if (result.getType() == GitPushRepoResult.Type.REJECTED_NO_FF) { + rejected.put(repository, result); + } + else if (result.getType() == GitPushRepoResult.Type.ERROR) { + errors.put(repository, result); + } + else if (result.getType() == GitPushRepoResult.Type.REJECTED_OTHER) { + customRejected.put(repository, result); + } + else { + successful.put(repository, result); + } + } + return new GroupedPushResult(successful, errors, rejected, customRejected); + } } diff --git a/plugin/src/main/java/git4idea/push/PushUpdateSettings.java b/plugin/src/main/java/git4idea/push/PushUpdateSettings.java index e3736da..526d524 100644 --- a/plugin/src/main/java/git4idea/push/PushUpdateSettings.java +++ b/plugin/src/main/java/git4idea/push/PushUpdateSettings.java @@ -19,33 +19,10 @@ import jakarta.annotation.Nonnull; // holds settings chosen in GitRejectedPushUpdate dialog to reuse if the next push is rejected again. -class PushUpdateSettings -{ - - private final boolean myUpdateAllRoots; - @Nonnull - private final UpdateMethod myUpdateMethod; - - PushUpdateSettings(boolean updateAllRoots, @Nonnull UpdateMethod updateMethod) - { - myUpdateAllRoots = updateAllRoots; - myUpdateMethod = updateMethod; - } - - boolean shouldUpdateAllRoots() - { - return myUpdateAllRoots; - } - - @Nonnull - UpdateMethod getUpdateMethod() - { - return myUpdateMethod; - } - - @Override - public String toString() - { - return String.format("UpdateSettings{myUpdateAllRoots=%s, myUpdateMethod=%s}", myUpdateAllRoots, myUpdateMethod); - } +record PushUpdateSettings(boolean shouldUpdateAllRoots, @Nonnull UpdateMethod updateMethod) { + @Deprecated + @Nonnull + UpdateMethod getUpdateMethod() { + return updateMethod(); + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitAbortRebaseProcess.java b/plugin/src/main/java/git4idea/rebase/GitAbortRebaseProcess.java index 8879755..0d944e8 100644 --- a/plugin/src/main/java/git4idea/rebase/GitAbortRebaseProcess.java +++ b/plugin/src/main/java/git4idea/rebase/GitAbortRebaseProcess.java @@ -92,8 +92,10 @@ class GitAbortRebaseProcess { @RequiredUIAccess void abortWithConfirmation() { - LOG.info("Abort rebase. " + (myRepositoryToAbort == null ? "Nothing to abort" : getShortRepositoryName(myRepositoryToAbort)) + - ". Roots to rollback: " + DvcsUtil.joinShortNames(myRepositoriesToRollback.keySet())); + LOG.info( + "Abort rebase. " + (myRepositoryToAbort == null ? "Nothing to abort" : getShortRepositoryName(myRepositoryToAbort)) + + ". Roots to rollback: " + DvcsUtil.joinShortNames(myRepositoriesToRollback.keySet()) + ); SimpleReference ref = SimpleReference.create(); Application application = myProject.getApplication(); application.invokeAndWait(() -> ref.set(confirmAbort()), application.getDefaultModalityState()); diff --git a/plugin/src/main/java/git4idea/rebase/GitInteractiveRebaseEditorHandler.java b/plugin/src/main/java/git4idea/rebase/GitInteractiveRebaseEditorHandler.java index dee3de9..b8450d8 100644 --- a/plugin/src/main/java/git4idea/rebase/GitInteractiveRebaseEditorHandler.java +++ b/plugin/src/main/java/git4idea/rebase/GitInteractiveRebaseEditorHandler.java @@ -15,223 +15,213 @@ */ package git4idea.rebase; -import java.io.Closeable; -import java.util.List; - -import jakarta.annotation.Nonnull; - -import consulo.application.ApplicationManager; -import consulo.application.CommonBundle; import consulo.logging.Logger; -import consulo.ui.ex.awt.Messages; -import consulo.util.lang.ref.Ref; +import consulo.platform.base.localize.CommonLocalize; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; +import consulo.ui.ex.awt.Messages; +import consulo.ui.ex.awt.UIUtil; +import consulo.util.lang.ref.SimpleReference; import consulo.virtualFileSystem.VirtualFile; import git4idea.DialogManager; import git4idea.commands.GitHandler; +import jakarta.annotation.Nonnull; + +import java.io.Closeable; +import java.util.List; /** * The handler for rebase editor request. The handler shows {@link GitRebaseEditor} * dialog with the specified file. If user accepts the changes, it saves file and returns 0, * otherwise it just returns error code. */ -public class GitInteractiveRebaseEditorHandler implements Closeable, GitRebaseEditorHandler -{ - /** - * The logger - */ - private final static Logger LOG = Logger.getInstance(GitInteractiveRebaseEditorHandler.class.getName()); - /** - * The service object that has created this handler - */ - private final GitRebaseEditorService myService; - /** - * The context project - */ - private final Project myProject; - /** - * The git repository root - */ - private final VirtualFile myRoot; - /** - * The handler that specified this editor - */ - private final GitHandler myHandler; - /** - * The handler number - */ - private final int myHandlerNo; - /** - * If true, the handler has been closed - */ - private boolean myIsClosed; - /** - * Set to true after rebase editor was shown - */ - protected boolean myRebaseEditorShown = false; +public class GitInteractiveRebaseEditorHandler implements Closeable, GitRebaseEditorHandler { + /** + * The logger + */ + private final static Logger LOG = Logger.getInstance(GitInteractiveRebaseEditorHandler.class); + /** + * The service object that has created this handler + */ + private final GitRebaseEditorService myService; + /** + * The context project + */ + @Nonnull + private final Project myProject; + /** + * The git repository root + */ + private final VirtualFile myRoot; + /** + * The handler that specified this editor + */ + private final GitHandler myHandler; + /** + * The handler number + */ + private final int myHandlerNo; + /** + * If true, the handler has been closed + */ + private boolean myIsClosed; + /** + * Set to true after rebase editor was shown + */ + protected boolean myRebaseEditorShown = false; - private boolean myNoopSituation; + private boolean myNoopSituation; - private boolean myEditorCancelled; + private boolean myEditorCancelled; - /** - * The constructor from fields that is expected to be - * accessed only from {@link GitRebaseEditorService}. - * - * @param service the service object that has created this handler - * @param project the context project - * @param root the git repository root - * @param handler the handler for process that needs this editor - */ - public GitInteractiveRebaseEditorHandler(@Nonnull final GitRebaseEditorService service, @Nonnull final Project project, @Nonnull final VirtualFile root, @Nonnull GitHandler handler) - { - myService = service; - myProject = project; - myRoot = root; - myHandler = handler; - myHandlerNo = service.registerHandler(this); - } + /** + * The constructor from fields that is expected to be + * accessed only from {@link GitRebaseEditorService}. + * + * @param service the service object that has created this handler + * @param project the context project + * @param root the git repository root + * @param handler the handler for process that needs this editor + */ + public GitInteractiveRebaseEditorHandler( + @Nonnull GitRebaseEditorService service, + @Nonnull Project project, + @Nonnull VirtualFile root, + @Nonnull GitHandler handler + ) { + myService = service; + myProject = project; + myRoot = root; + myHandler = handler; + myHandlerNo = service.registerHandler(this); + } - /** - * @return the handler for the process that started this editor - */ - public GitHandler getHandler() - { - return myHandler; - } + /** + * @return the handler for the process that started this editor + */ + @Override + public GitHandler getHandler() { + return myHandler; + } - /** - * Edit commits request - * - * @param path the path to editing - * @return the exit code to be returned from editor - */ - public int editCommits(final String path) - { - ensureOpen(); - final Ref isSuccess = new Ref<>(); - ApplicationManager.getApplication().invokeAndWait(new Runnable() - { - public void run() - { - try - { - myEditorCancelled = false; - myNoopSituation = false; - if(myRebaseEditorShown) - { - GitRebaseUnstructuredEditor editor = new GitRebaseUnstructuredEditor(myProject, myRoot, path); - DialogManager.show(editor); - if(editor.isOK()) - { - editor.save(); - } - else - { - myEditorCancelled = true; - } - isSuccess.set(true); - return; - } - else - { - setRebaseEditorShown(); - GitInteractiveRebaseFile rebaseFile = new GitInteractiveRebaseFile(myProject, myRoot, path); - try - { - List entries = rebaseFile.load(); - GitRebaseEditor editor = new GitRebaseEditor(myProject, myRoot, entries); - DialogManager.show(editor); - if(editor.isOK()) - { - rebaseFile.save(editor.getEntries()); - isSuccess.set(true); - return; - } - else - { - rebaseFile.cancel(); - myEditorCancelled = true; - } - } - catch(GitInteractiveRebaseFile.NoopException e) - { - LOG.info("Noop situation while rebasing " + myRoot); - String message = "There are no commits to rebase because the current branch is directly below the base branch, " + - "or they point to the same commit (the 'noop' situation).\n" + - "Do you want to continue (this will reset the current branch to the base branch)?"; - int rebase = DialogManager.showOkCancelDialog(myProject, message, "Git Rebase", CommonBundle.getOkButtonText(), CommonBundle.getCancelButtonText(), - Messages.getQuestionIcon()); - if(rebase == Messages.OK) - { - isSuccess.set(true); - myNoopSituation = true; - return; - } - else - { - myEditorCancelled = true; - } - } - } - } - catch(Exception e) - { - LOG.error("Failed to edit the git rebase file: " + path, e); - } - isSuccess.set(false); - } - }); - return (isSuccess.isNull() || !isSuccess.get().booleanValue()) ? GitRebaseEditorMain.ERROR_EXIT_CODE : 0; - } + /** + * Edit commits request + * + * @param path the path to editing + * @return the exit code to be returned from editor + */ + @Override + @RequiredUIAccess + public int editCommits(String path) { + ensureOpen(); + SimpleReference isSuccess = new SimpleReference<>(); + myProject.getApplication().invokeAndWait(() -> { + try { + myEditorCancelled = false; + myNoopSituation = false; + if (myRebaseEditorShown) { + GitRebaseUnstructuredEditor editor = new GitRebaseUnstructuredEditor(myProject, myRoot, path); + DialogManager.show(editor); + if (editor.isOK()) { + editor.save(); + } + else { + myEditorCancelled = true; + } + isSuccess.set(true); + return; + } + else { + setRebaseEditorShown(); + GitInteractiveRebaseFile rebaseFile = new GitInteractiveRebaseFile(myProject, myRoot, path); + try { + List entries = rebaseFile.load(); + GitRebaseEditor editor = new GitRebaseEditor(myProject, myRoot, entries); + DialogManager.show(editor); + if (editor.isOK()) { + rebaseFile.save(editor.getEntries()); + isSuccess.set(true); + return; + } + else { + rebaseFile.cancel(); + myEditorCancelled = true; + } + } + catch (GitInteractiveRebaseFile.NoopException e) { + LOG.info("Noop situation while rebasing " + myRoot); + String message = + "There are no commits to rebase because the current branch is directly below the base branch, " + + "or they point to the same commit (the 'noop' situation).\n" + + "Do you want to continue (this will reset the current branch to the base branch)?"; + int rebase = DialogManager.showOkCancelDialog( + myProject, + message, + "Git Rebase", + CommonLocalize.buttonOk().get(), + CommonLocalize.buttonCancel().get(), + UIUtil.getQuestionIcon() + ); + if (rebase == Messages.OK) { + isSuccess.set(true); + myNoopSituation = true; + return; + } + else { + myEditorCancelled = true; + } + } + } + } + catch (Exception e) { + LOG.error("Failed to edit the git rebase file: " + path, e); + } + isSuccess.set(false); + }); + return (isSuccess.isNull() || !isSuccess.get()) ? GitRebaseEditorMain.ERROR_EXIT_CODE : 0; + } - /** - * This method is invoked to indicate that this editor will be invoked in the rebase continuation action. - */ - public void setRebaseEditorShown() - { - myRebaseEditorShown = true; - } + /** + * This method is invoked to indicate that this editor will be invoked in the rebase continuation action. + */ + public void setRebaseEditorShown() { + myRebaseEditorShown = true; + } - /** - * Check that handler has not yet been closed - */ - private void ensureOpen() - { - if(myIsClosed) - { - throw new IllegalStateException("The handler was already closed"); - } - } + /** + * Check that handler has not yet been closed + */ + private void ensureOpen() { + if (myIsClosed) { + throw new IllegalStateException("The handler was already closed"); + } + } - /** - * Stop using the handler - */ - public void close() - { - ensureOpen(); - myIsClosed = true; - myService.unregisterHandler(myHandlerNo); - } + /** + * Stop using the handler + */ + @Override + public void close() { + ensureOpen(); + myIsClosed = true; + myService.unregisterHandler(myHandlerNo); + } - /** - * @return the handler number - */ - public int getHandlerNo() - { - return myHandlerNo; - } + /** + * @return the handler number + */ + public int getHandlerNo() { + return myHandlerNo; + } - /** - * Tells if there was a "noop" situation during rebase (no commits were rebase, just the label was moved). - */ - public boolean wasNoopSituationDetected() - { - return myNoopSituation; - } + /** + * Tells if there was a "noop" situation during rebase (no commits were rebase, just the label was moved). + */ + public boolean wasNoopSituationDetected() { + return myNoopSituation; + } - public boolean wasEditorCancelled() - { - return myEditorCancelled; - } + public boolean wasEditorCancelled() { + return myEditorCancelled; + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.form b/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.form deleted file mode 100644 index f3d8c31..0000000 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.form +++ /dev/null @@ -1,43 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.java b/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.java index 5b67467..e2b557c 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseActionDialog.java @@ -15,10 +15,17 @@ */ package git4idea.rebase; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; +import consulo.git.localize.GitLocalize; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.ui.ex.awt.DialogWrapper; +import consulo.ui.ex.awt.JBUI; import consulo.virtualFileSystem.VirtualFile; import git4idea.util.GitUIUtil; +import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import javax.swing.*; @@ -28,47 +35,174 @@ * The rebase action dialog */ public class GitRebaseActionDialog extends DialogWrapper { - /** - * The root selector - */ - private JComboBox myGitRootComboBox; - /** - * The root panel - */ - private JPanel myPanel; + /** + * The root selector + */ + private JComboBox myGitRootComboBox; + /** + * The root panel + */ + private JPanel myPanel; - /** - * A constructor - * - * @param project the project to select - * @param title the dialog title - * @param roots the git repository roots for the project - * @param defaultRoot the guessed default root - */ - public GitRebaseActionDialog(Project project, String title, List roots, VirtualFile defaultRoot) { - super(project, true); - GitUIUtil.setupRootChooser(project, roots, defaultRoot, myGitRootComboBox, null); - setTitle(title); - setOKButtonText(title); - init(); - } + /** + * A constructor + * + * @param project the project to select + * @param title the dialog title + * @param roots the git repository roots for the project + * @param defaultRoot the guessed default root + */ + public GitRebaseActionDialog(Project project, @Nonnull LocalizeValue title, List roots, VirtualFile defaultRoot) { + super(project, true); + GitUIUtil.setupRootChooser(project, roots, defaultRoot, myGitRootComboBox, null); + setTitle(title); + setOKButtonText(title); + init(); + } - /** - * Show dialog and select root - * - * @return selected root or null if the dialog has been cancelled - */ - @Nullable - public VirtualFile selectRoot() { - return isOK() ? (VirtualFile)myGitRootComboBox.getSelectedItem() : null; - } + /** + * Show dialog and select root + * + * @return selected root or null if the dialog has been cancelled + */ + @Nullable + public VirtualFile selectRoot() { + return isOK() ? (VirtualFile) myGitRootComboBox.getSelectedItem() : null; + } + /** + * {@inheritDoc} + */ + @Override + protected JComponent createCenterPanel() { + return myPanel; + } - /** - * {@inheritDoc} - */ - protected JComponent createCenterPanel() { - return myPanel; - } + { +// GUI initializer generated by Consulo GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + myPanel = new JPanel(); + myPanel.setLayout(new GridLayoutManager(3, 2, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.rebaseActionMessage().get()); + myPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.commonGitRoot().get()); + myPanel.add( + label2, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + myPanel.add( + spacer1, + new GridConstraints( + 2, + 0, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_VERTICAL, + 1, + GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null, + 0, + false + ) + ); + myGitRootComboBox = new JComboBox(); + myGitRootComboBox.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myPanel.add( + myGitRootComboBox, + new GridConstraints( + 1, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + label2.setLabelFor(myGitRootComboBox); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myPanel; + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.form b/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.form deleted file mode 100644 index 1fed71e..0000000 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.form +++ /dev/null @@ -1,217 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.java b/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.java index 7231114..666a1de 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseDialog.java @@ -15,6 +15,9 @@ */ package git4idea.rebase; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; import consulo.git.localize.GitLocalize; import consulo.ide.ServiceManager; import consulo.logging.Logger; @@ -22,6 +25,7 @@ import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.ComboBox; import consulo.ui.ex.awt.DialogWrapper; +import consulo.ui.ex.awt.JBUI; import consulo.ui.ex.awt.event.DocumentAdapter; import consulo.util.lang.StringUtil; import consulo.versionControlSystem.VcsException; @@ -160,14 +164,16 @@ public GitRebaseDialog(Project project, List roots, VirtualFile def myProject = project; mySettings = ServiceManager.getService(myProject, GitRebaseSettings.class); myRepositoryManager = GitUtil.getRepositoryManager(myProject); - final Runnable validateRunnable = this::validateFields; - myOntoValidator = new GitReferenceValidator(myProject, + Runnable validateRunnable = this::validateFields; + myOntoValidator = new GitReferenceValidator( + myProject, myGitRootComboBox, GitUIUtil.getTextField(myOntoComboBox), myOntoValidateButton, validateRunnable ); - myFromValidator = new GitReferenceValidator(myProject, + myFromValidator = new GitReferenceValidator( + myProject, myGitRootComboBox, GitUIUtil.getTextField(myFromComboBox), myFromValidateButton, @@ -288,15 +294,16 @@ else if (myOntoValidator.isInvalid()) { private void setupBranches() { GitUIUtil.getTextField(myOntoComboBox).getDocument().addDocumentListener(new DocumentAdapter() { @Override - protected void textChanged(final DocumentEvent e) { + protected void textChanged(DocumentEvent e) { validateFields(); } }); - final ActionListener rootListener = e -> { + @RequiredUIAccess + ActionListener rootListener = e -> { loadRefs(); updateBranches(); }; - final ActionListener showListener = e -> updateOntoFrom(); + ActionListener showListener = e -> updateOntoFrom(); myShowRemoteBranchesCheckBox.addActionListener(showListener); myShowTagsCheckBox.addActionListener(showListener); rootListener.actionPerformed(null); @@ -324,7 +331,7 @@ private void updateBranches() { } /** - * Update onto and from comboboxes. + * Update onto and from combo-boxes. */ protected void updateOntoFrom() { String onto = GitUIUtil.getTextField(myOntoComboBox).getText(); @@ -360,7 +367,7 @@ protected void loadRefs() { myLocalBranches.clear(); myRemoteBranches.clear(); myTags.clear(); - final VirtualFile root = gitRoot(); + VirtualFile root = gitRoot(); GitRepository repository = GitUtil.getRepositoryManager(myProject).getRepositoryForRoot(root); if (repository != null) { myLocalBranches.addAll(repository.getBranches().getLocalBranches()); @@ -383,8 +390,8 @@ protected void loadRefs() { @RequiredUIAccess private void updateTrackedBranch() { try { - final VirtualFile root = gitRoot(); - String currentBranch = (String)myBranchComboBox.getSelectedItem(); + VirtualFile root = gitRoot(); + String currentBranch = (String) myBranchComboBox.getSelectedItem(); GitBranch trackedBranch = null; if (currentBranch != null) { String remote = GitConfigUtil.getValue(myProject, root, "branch." + currentBranch + ".remote"); @@ -419,7 +426,7 @@ private void updateTrackedBranch() { * @return the currently selected git root */ public VirtualFile gitRoot() { - return (VirtualFile)myGitRootComboBox.getSelectedItem(); + return (VirtualFile) myGitRootComboBox.getSelectedItem(); } @Nonnull @@ -429,7 +436,7 @@ public GitRepository getSelectedRepository() { @Nonnull public GitRebaseParams getSelectedParams() { - String selectedBranch = (String)myBranchComboBox.getSelectedItem(); + String selectedBranch = (String) myBranchComboBox.getSelectedItem(); String branch = myCurrentBranch != null && !myCurrentBranch.getName().equals(selectedBranch) ? selectedBranch : null; String from = GitUIUtil.getTextField(myFromComboBox).getText(); @@ -471,4 +478,571 @@ protected JComponent createCenterPanel() { protected String getHelpId() { return "reference.VersionControl.Git.Rebase"; } + + { +// GUI initializer generated by Consulo GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + myPanel = new JPanel(); + myPanel.setLayout(new GridLayoutManager(8, 3, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.commonGitRoot().get()); + myPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + myPanel.add( + spacer1, + new GridConstraints( + 7, + 0, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_VERTICAL, + 1, + GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null, + 0, + false + ) + ); + myGitRootComboBox = new ComboBox(); + myGitRootComboBox.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myPanel.add( + myGitRootComboBox, + new GridConstraints( + 0, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.rebaseBranch().get()); + myPanel.add( + label2, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myBranchComboBox = new ComboBox<>(); + myBranchComboBox.setToolTipText(GitLocalize.rebaseBranchTooltip().get()); + myPanel.add( + myBranchComboBox, + new GridConstraints( + 1, + 1, + 1, + 2, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label3 = new JLabel(); + this.$$$loadLabelText$$$(label3, GitLocalize.rebaseOnto().get()); + myPanel.add( + label3, + new GridConstraints( + 3, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myOntoComboBox = new ComboBox<>(); + myOntoComboBox.setEditable(true); + myOntoComboBox.setToolTipText(GitLocalize.rebaseOntoTooltip().get()); + myPanel.add( + myOntoComboBox, + new GridConstraints( + 3, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myOntoValidateButton = new JButton(); + this.$$$loadButtonText$$$(myOntoValidateButton, GitLocalize.rebaseOntoValidate().get()); + myOntoValidateButton.setToolTipText(GitLocalize.rebaseValdateOntoTooltip().get()); + myPanel.add( + myOntoValidateButton, + new GridConstraints( + 3, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label4 = new JLabel(); + this.$$$loadLabelText$$$(label4, GitLocalize.rebaseMergeStrategy().get()); + myPanel.add( + label4, + new GridConstraints( + 6, + 0, + 1, + 1, + GridConstraints.ANCHOR_NORTHWEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label5 = new JLabel(); + this.$$$loadLabelText$$$(label5, GitLocalize.rebaseFrom().get()); + myPanel.add( + label5, + new GridConstraints( + 4, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myFromComboBox = new ComboBox<>(); + myFromComboBox.setEditable(true); + myFromComboBox.setToolTipText(GitLocalize.rebaseFromTooltip().get()); + myPanel.add( + myFromComboBox, + new GridConstraints( + 4, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myFromValidateButton = new JButton(); + this.$$$loadButtonText$$$(myFromValidateButton, GitLocalize.rebaseValidateFrom().get()); + myFromValidateButton.setToolTipText(GitLocalize.rebaseValidateFromTooltip().get()); + myPanel.add( + myFromValidateButton, + new GridConstraints( + 4, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(2, 2, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel1, + new GridConstraints( + 6, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myMergeStrategyComboBox = new ComboBox<>(); + myMergeStrategyComboBox.setToolTipText(GitLocalize.rebaseMergeStrategyTooltip().get()); + panel1.add( + myMergeStrategyComboBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer2 = new Spacer(); + panel1.add( + spacer2, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + myDoNotUseMergeCheckBox = new JCheckBox(); + myDoNotUseMergeCheckBox.setSelected(false); + this.$$$loadButtonText$$$(myDoNotUseMergeCheckBox, GitLocalize.rebaseNoMerge().get()); + myDoNotUseMergeCheckBox.setToolTipText(GitLocalize.rebaseNoMergeTooltip().get()); + panel1.add( + myDoNotUseMergeCheckBox, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + 1, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 3, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel2, + new GridConstraints( + 2, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer3 = new Spacer(); + panel2.add( + spacer3, + new GridConstraints( + 0, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + myPreserveMergesCheckBox = new JCheckBox(); + myPreserveMergesCheckBox.setSelected(false); + this.$$$loadButtonText$$$(myPreserveMergesCheckBox, GitLocalize.rebasePreserveMerges().get()); + myPreserveMergesCheckBox.setToolTipText(GitLocalize.rebasePreserveMergesTooltip().get()); + panel2.add( + myPreserveMergesCheckBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myInteractiveCheckBox = new JCheckBox(); + myInteractiveCheckBox.setEnabled(true); + myInteractiveCheckBox.setSelected(true); + this.$$$loadButtonText$$$(myInteractiveCheckBox, GitLocalize.rebaseInteractive().get()); + myInteractiveCheckBox.setToolTipText(GitLocalize.rebaseInteractiveTooltip().get()); + panel2.add( + myInteractiveCheckBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel3 = new JPanel(); + panel3.setLayout(new GridLayoutManager(1, 3, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel3, + new GridConstraints( + 5, + 1, + 1, + 2, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myShowTagsCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myShowTagsCheckBox, GitLocalize.regaseShowTags().get()); + myShowTagsCheckBox.setToolTipText(GitLocalize.rebaseShowTagsTooltip().get()); + panel3.add( + myShowTagsCheckBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myShowRemoteBranchesCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myShowRemoteBranchesCheckBox, GitLocalize.rebaseShowRemoteBranches().get()); + myShowRemoteBranchesCheckBox.setToolTipText(GitLocalize.rebaseShowRemoteBranchesTooltip().get()); + panel3.add( + myShowRemoteBranchesCheckBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer4 = new Spacer(); + panel3.add( + spacer4, + new GridConstraints( + 0, + 2, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + label1.setLabelFor(myGitRootComboBox); + label2.setLabelFor(myBranchComboBox); + label3.setLabelFor(myOntoComboBox); + label4.setLabelFor(myMergeStrategyComboBox); + label5.setLabelFor(myFromComboBox); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myPanel; + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseEditor.java b/plugin/src/main/java/git4idea/rebase/GitRebaseEditor.java index 377dd18..e9ed3c7 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseEditor.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseEditor.java @@ -15,10 +15,10 @@ */ package git4idea.rebase; -import consulo.application.AllIcons; import consulo.application.dumb.DumbAware; import consulo.dataContext.DataProvider; import consulo.git.localize.GitLocalize; +import consulo.platform.base.icon.PlatformIconGroup; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.CopyProvider; @@ -60,11 +60,9 @@ public class GitRebaseEditor extends DialogWrapper implements DataProvider { @Nonnull private final CopyProvider myCopyProvider; - protected GitRebaseEditor( - @Nonnull Project project, - @Nonnull VirtualFile gitRoot, - @Nonnull List entries - ) throws IOException { + protected GitRebaseEditor(@Nonnull Project project, @Nonnull VirtualFile gitRoot, @Nonnull List entries) + throws IOException { + super(project, true); myProject = project; myRoot = gitRoot; @@ -76,9 +74,9 @@ protected GitRebaseEditor( myCommitsTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); myCommitsTable.setIntercellSpacing(JBUI.emptySize()); - final JComboBox editorComboBox = new ComboBox(); - for (Object option : GitRebaseEntry.Action.values()) { - editorComboBox.addItem(option); + JComboBox editorComboBox = new ComboBox<>(); + for (GitRebaseEntry.Action action : GitRebaseEntry.Action.values()) { + editorComboBox.addItem(action); } TableColumn actionColumn = myCommitsTable.getColumnModel().getColumn(MyTableModel.ACTION_COLUMN); actionColumn.setCellEditor(new DefaultCellEditor(editorComboBox)); @@ -123,7 +121,7 @@ private void adjustColumnWidth(int columnIndex) { } private void validateFields() { - final List entries = myTableModel.myEntries; + List entries = myTableModel.myEntries; if (entries.size() == 0) { setErrorText(GitLocalize.rebaseEditorInvalidEntryset()); setOKActionEnabled(false); @@ -230,7 +228,7 @@ public Object getValueAt(int rowIndex, int columnIndex) { } @Override - public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { assert columnIndex == ACTION_COLUMN; if (ArrayUtil.indexOf(myLastEditableSelectedRows, rowIndex) > -1) { @@ -288,7 +286,7 @@ private void setRowAction(@Nonnull Object aValue, int rowIndex, int columnIndex) } @Override - public boolean isCellEditable(final int rowIndex, final int columnIndex) { + public boolean isCellEditable(int rowIndex, int columnIndex) { myLastEditableSelectedRows = myCommitsTable.getSelectedRows(); return columnIndex == ACTION_COLUMN; } @@ -296,11 +294,11 @@ public boolean isCellEditable(final int rowIndex, final int columnIndex) { public void moveRows(@Nonnull int[] rows, @Nonnull MoveDirection direction) { myCommitsTable.removeEditor(); - final ContiguousIntIntervalTracker selectionInterval = new ContiguousIntIntervalTracker(); - final ContiguousIntIntervalTracker rowsUpdatedInterval = new ContiguousIntIntervalTracker(); + ContiguousIntIntervalTracker selectionInterval = new ContiguousIntIntervalTracker(); + ContiguousIntIntervalTracker rowsUpdatedInterval = new ContiguousIntIntervalTracker(); for (int row : direction.preprocessRowIndexes(rows)) { - final int targetIndex = row + direction.offset(); + int targetIndex = row + direction.offset(); assertIndexInRange(row, targetIndex); Collections.swap(myEntries, row, targetIndex); @@ -377,7 +375,7 @@ public int[] preprocessRowIndexes(int[] selection) { private class MyDiffAction extends ToolbarDecorator.ElementActionButton implements DumbAware { MyDiffAction() { - super("View", "View commit contents", AllIcons.Actions.Diff); + super("View", "View commit contents", PlatformIconGroup.actionsDiff()); registerCustomShortcutSet(CommonShortcuts.getDiff(), myCommitsTable); } @@ -385,7 +383,7 @@ private class MyDiffAction extends ToolbarDecorator.ElementActionButton implemen @RequiredUIAccess public void actionPerformed(@Nonnull AnActionEvent e) { int row = myCommitsTable.getSelectedRow(); - assert row >= 0 && row < myTableModel.getRowCount(); + assert 0 <= row && row < myTableModel.getRowCount(); GitRebaseEntry entry = myTableModel.myEntries.get(row); GitUtil.showSubmittedFiles(myProject, entry.getCommit(), myRoot, false, false); } @@ -404,6 +402,7 @@ public MoveUpDownActionListener(@Nonnull MoveDirection direction) { } @Override + @RequiredUIAccess public void run(AnActionButton button) { myTableModel.moveRows(myCommitsTable.getSelectedRows(), direction); } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorHandler.java b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorHandler.java index 5a9ca12..4e5b439 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorHandler.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorHandler.java @@ -21,16 +21,16 @@ * The interface */ public interface GitRebaseEditorHandler { - /** - * Edit commits request - * - * @param path the path to editing - * @return the exit code to be returned from editor - */ - int editCommits(String path); + /** + * Edit commits request + * + * @param path the path to editing + * @return the exit code to be returned from editor + */ + int editCommits(String path); - /** - * @return the handler for the git process - */ - GitHandler getHandler(); + /** + * @return the handler for the git process + */ + GitHandler getHandler(); } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorMain.java b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorMain.java index 585a2c5..bdc79dc 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorMain.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorMain.java @@ -18,7 +18,6 @@ import jakarta.annotation.Nonnull; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; -import org.jetbrains.annotations.NonNls; import java.io.File; import java.net.URL; @@ -32,110 +31,95 @@ * registered on the host passed as the first parameter. The application * exits with exit code returned from the service. */ -public class GitRebaseEditorMain -{ - /** - * The environment variable for handler no - */ - @NonNls - @Nonnull - public static final String IDEA_REBASE_HANDER_NO = "IDEA_REBASE_HANDER_NO"; - /** - * The exit code used to indicate that editing was canceled or has failed in some other way. - */ - public final static int ERROR_EXIT_CODE = 2; - /** - * Rebase editor handler name - */ - @NonNls - static final String HANDLER_NAME = "Git4ideaRebaseEditorHandler"; - /** - * The prefix for cygwin files - */ - private static final String CYGDRIVE_PREFIX = "/cygdrive/"; +public class GitRebaseEditorMain { + /** + * The environment variable for handler no + */ + @Nonnull + public static final String IDEA_REBASE_HANDER_NO = "IDEA_REBASE_HANDER_NO"; + /** + * The exit code used to indicate that editing was canceled or has failed in some other way. + */ + public final static int ERROR_EXIT_CODE = 2; + /** + * Rebase editor handler name + */ + static final String HANDLER_NAME = "Git4ideaRebaseEditorHandler"; + /** + * The prefix for cygwin files + */ + private static final String CYGDRIVE_PREFIX = "/cygdrive/"; - /** - * A private constructor for static class - */ - private GitRebaseEditorMain() - { - } + /** + * A private constructor for static class + */ + private GitRebaseEditorMain() { + } - /** - * The application entry point - * - * @param args application arguments - */ - @SuppressWarnings( - { - "UseOfSystemOutOrSystemErr", - "HardCodedStringLiteral", - "CallToPrintStackTrace", - "UseOfObsoleteCollectionType" - }) - public static void main(String[] args) - { - if(args.length != 2) - { - System.err.println("Invalid amount of arguments: " + Arrays.asList(args)); - System.exit(ERROR_EXIT_CODE); - } - int port; - try - { - port = Integer.parseInt(args[0]); - } - catch(NumberFormatException ex) - { - System.err.println("Invalid port number: " + args[0]); - System.exit(ERROR_EXIT_CODE); - return; - } - final String handlerValue = System.getenv(IDEA_REBASE_HANDER_NO); - if(handlerValue == null) - { - System.err.println("Handler no is not specified"); - System.exit(ERROR_EXIT_CODE); - } - int handler; - try - { - handler = Integer.parseInt(handlerValue); - } - catch(NumberFormatException ex) - { - System.err.println("Invalid handler number: " + handlerValue); - System.exit(ERROR_EXIT_CODE); - return; - } - String file = args[1]; - try - { - XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl(); - clientConfig.setServerURL(new URL("http://127.0.0.1:" + port + "/RPC2")); - XmlRpcClient client = new XmlRpcClient(); - client.setConfig(clientConfig); + /** + * The application entry point + * + * @param args application arguments + */ + @SuppressWarnings( + { + "UseOfSystemOutOrSystemErr", + "HardCodedStringLiteral", + "CallToPrintStackTrace", + "UseOfObsoleteCollectionType" + }) + public static void main(String[] args) { + if (args.length != 2) { + System.err.println("Invalid amount of arguments: " + Arrays.asList(args)); + System.exit(ERROR_EXIT_CODE); + } + int port; + try { + port = Integer.parseInt(args[0]); + } + catch (NumberFormatException ex) { + System.err.println("Invalid port number: " + args[0]); + System.exit(ERROR_EXIT_CODE); + return; + } + String handlerValue = System.getenv(IDEA_REBASE_HANDER_NO); + if (handlerValue == null) { + System.err.println("Handler no is not specified"); + System.exit(ERROR_EXIT_CODE); + } + int handler; + try { + handler = Integer.parseInt(handlerValue); + } + catch (NumberFormatException ex) { + System.err.println("Invalid handler number: " + handlerValue); + System.exit(ERROR_EXIT_CODE); + return; + } + String file = args[1]; + try { + XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl(); + clientConfig.setServerURL(new URL("http://127.0.0.1:" + port + "/RPC2")); + XmlRpcClient client = new XmlRpcClient(); + client.setConfig(clientConfig); - List params = new ArrayList(); - params.add(handler); - if(System.getProperty("os.name").toLowerCase().startsWith("windows") && file.startsWith(CYGDRIVE_PREFIX)) - { - int p = CYGDRIVE_PREFIX.length(); - file = file.substring(p, p + 1) + ":" + file.substring(p + 1); - } - params.add(new File(file).getAbsolutePath()); - Integer exitCode = (Integer) client.execute(HANDLER_NAME + ".editCommits", params); - if(exitCode == null) - { - exitCode = ERROR_EXIT_CODE; - } - System.exit(exitCode.intValue()); - } - catch(Exception e) - { - System.err.println("Unable to contact IDEA: " + e); - e.printStackTrace(); - System.exit(ERROR_EXIT_CODE); - } - } + List params = new ArrayList<>(); + params.add(handler); + if (System.getProperty("os.name").toLowerCase().startsWith("windows") && file.startsWith(CYGDRIVE_PREFIX)) { + int p = CYGDRIVE_PREFIX.length(); + file = file.substring(p, p + 1) + ":" + file.substring(p + 1); + } + params.add(new File(file).getAbsolutePath()); + Integer exitCode = (Integer) client.execute(HANDLER_NAME + ".editCommits", params); + if (exitCode == null) { + exitCode = ERROR_EXIT_CODE; + } + System.exit(exitCode); + } + catch (Exception e) { + System.err.println("Unable to contact IDEA: " + e); + e.printStackTrace(); + System.exit(ERROR_EXIT_CODE); + } + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorService.java b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorService.java index 62ed56b..80b1278 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseEditorService.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseEditorService.java @@ -23,15 +23,14 @@ import consulo.ide.ServiceManager; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; +import jakarta.annotation.Nonnull; import jakarta.inject.Singleton; import org.apache.commons.codec.DecoderException; import org.apache.ws.commons.serialize.DOMSerializer; import org.apache.xmlrpc.XmlRpcConfig; import org.apache.xmlrpc.client.XmlRpcClient; -import org.jetbrains.annotations.NonNls; import org.jetbrains.git4idea.util.ScriptGenerator; -import jakarta.annotation.Nonnull; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; @@ -44,152 +43,145 @@ @ServiceAPI(ComponentScope.APPLICATION) @ServiceImpl public class GitRebaseEditorService { - /** - * The editor command that is set to env variable - */ - private String myEditorCommand; - /** - * The lock object - */ - private final Object myScriptLock = new Object(); - /** - * The handlers to use - */ - private final Map myHandlers = new HashMap<>(); - /** - * The lock for the handlers - */ - private final Object myHandlersLock = new Object(); - /** - * Random number generator - */ - private static final Random oursRandom = new SecureRandom(); - /** - * The prefix for rebase editors - */ - @NonNls - private static final String GIT_REBASE_EDITOR_PREFIX = "git-rebase-editor-"; + /** + * The editor command that is set to env variable + */ + private String myEditorCommand; + /** + * The lock object + */ + private final Object myScriptLock = new Object(); + /** + * The handlers to use + */ + private final Map myHandlers = new HashMap<>(); + /** + * The lock for the handlers + */ + private final Object myHandlersLock = new Object(); + /** + * Random number generator + */ + private static final Random oursRandom = new SecureRandom(); + /** + * The prefix for rebase editors + */ + private static final String GIT_REBASE_EDITOR_PREFIX = "git-rebase-editor-"; - /** - * @return an instance of the server - */ - @Nonnull - public static GitRebaseEditorService getInstance() { - final GitRebaseEditorService service = ServiceManager.getService(GitRebaseEditorService.class); - if (service == null) { - throw new IllegalStateException("The service " + GitRebaseEditorService.class.getName() + " cannot be located"); + /** + * @return an instance of the server + */ + @Nonnull + public static GitRebaseEditorService getInstance() { + return ServiceManager.getService(GitRebaseEditorService.class); } - return service; - } - private void addInternalHandler() { - XmlRpcServer xmlRpcServer = XmlRpcServer.getInstance(); - if (!xmlRpcServer.hasHandler(GitRebaseEditorMain.HANDLER_NAME)) { - xmlRpcServer.addHandler(GitRebaseEditorMain.HANDLER_NAME, new InternalHandler()); + private void addInternalHandler() { + XmlRpcServer xmlRpcServer = XmlRpcServer.getInstance(); + if (!xmlRpcServer.hasHandler(GitRebaseEditorMain.HANDLER_NAME)) { + xmlRpcServer.addHandler(GitRebaseEditorMain.HANDLER_NAME, new InternalHandler()); + } } - } - /** - * Get editor command - * - * @return the editor command - */ - @Nonnull - public synchronized String getEditorCommand() { - synchronized (myScriptLock) { - if (myEditorCommand == null) { - ScriptGenerator generator = new ScriptGenerator(GIT_REBASE_EDITOR_PREFIX, GitRebaseEditorMain.class); - generator.addInternal(Integer.toString(BuiltInServerManager.getInstance().getPort())); - generator.addClasses(XmlRpcClient.class, XmlRpcConfig.class, DOMSerializer.class, DecoderException.class); - myEditorCommand = generator.commandLine(); - } - return myEditorCommand; + /** + * Get editor command + * + * @return the editor command + */ + @Nonnull + public synchronized String getEditorCommand() { + synchronized (myScriptLock) { + if (myEditorCommand == null) { + ScriptGenerator generator = new ScriptGenerator(GIT_REBASE_EDITOR_PREFIX, GitRebaseEditorMain.class); + generator.addInternal(Integer.toString(BuiltInServerManager.getInstance().getPort())); + generator.addClasses(XmlRpcClient.class, XmlRpcConfig.class, DOMSerializer.class, DecoderException.class); + myEditorCommand = generator.commandLine(); + } + return myEditorCommand; + } } - } - /** - * Register the handler in the service - * - * @param handler the handler to register - * @return the handler identifier - */ - public int registerHandler(GitRebaseEditorHandler handler) { - addInternalHandler(); - Integer rc = null; - synchronized (myHandlersLock) { - for (int i = Integer.MAX_VALUE; i > 0; i--) { - int code = Math.abs(oursRandom.nextInt()); - // note that code might still be negative at this point if it is Integer.MIN_VALUE. - if (code > 0 && !myHandlers.containsKey(code)) { - rc = code; - break; + /** + * Register the handler in the service + * + * @param handler the handler to register + * @return the handler identifier + */ + public int registerHandler(GitRebaseEditorHandler handler) { + addInternalHandler(); + Integer rc = null; + synchronized (myHandlersLock) { + for (int i = Integer.MAX_VALUE; i > 0; i--) { + int code = Math.abs(oursRandom.nextInt()); + // note that code might still be negative at this point if it is Integer.MIN_VALUE. + if (code > 0 && !myHandlers.containsKey(code)) { + rc = code; + break; + } + } + if (rc == null) { + throw new IllegalStateException("There is a problem with random number allocation"); + } + myHandlers.put(rc, handler); } - } - if (rc == null) { - throw new IllegalStateException("There is a problem with random number allocation"); - } - myHandlers.put(rc, handler); + return rc; } - return rc; - } - - /** - * Unregister handler - * - * @param handlerNo the handler number. - */ - public void unregisterHandler(final int handlerNo) { - synchronized (myHandlersLock) { - if (myHandlers.remove(handlerNo) == null) { - throw new IllegalStateException("The handler " + handlerNo + " has been already removed"); - } + /** + * Unregister handler + * + * @param handlerNo the handler number. + */ + public void unregisterHandler(int handlerNo) { + synchronized (myHandlersLock) { + if (myHandlers.remove(handlerNo) == null) { + throw new IllegalStateException("The handler " + handlerNo + " has been already removed"); + } + } } - } - /** - * Get handler - * - * @param handlerNo the handler number. - */ - @Nonnull - GitRebaseEditorHandler getHandler(final int handlerNo) { - synchronized (myHandlersLock) { - GitRebaseEditorHandler h = myHandlers.get(handlerNo); - if (h == null) { - throw new IllegalStateException("The handler " + handlerNo + " is not registered"); - } - return h; + /** + * Get handler + * + * @param handlerNo the handler number. + */ + @Nonnull + GitRebaseEditorHandler getHandler(int handlerNo) { + synchronized (myHandlersLock) { + GitRebaseEditorHandler h = myHandlers.get(handlerNo); + if (h == null) { + throw new IllegalStateException("The handler " + handlerNo + " is not registered"); + } + return h; + } } - } - - /** - * Configure handler with editor - * - * @param h the handler to configure - * @param editorNo the editor number - */ - public void configureHandler(GitLineHandler h, int editorNo) { - h.setEnvironment(GitCommand.GIT_EDITOR_ENV, getEditorCommand()); - h.setEnvironment(GitRebaseEditorMain.IDEA_REBASE_HANDER_NO, Integer.toString(editorNo)); - } - - /** - * The internal xml rcp handler - */ - public class InternalHandler { /** - * Edit commits for the rebase operation + * Configure handler with editor * - * @param handlerNo the handler no - * @param path the path to edit - * @return exit code + * @param h the handler to configure + * @param editorNo the editor number */ - @SuppressWarnings({"UnusedDeclaration"}) - public int editCommits(int handlerNo, String path) { - GitRebaseEditorHandler editor = getHandler(handlerNo); - return editor.editCommits(path); + public void configureHandler(GitLineHandler h, int editorNo) { + h.setEnvironment(GitCommand.GIT_EDITOR_ENV, getEditorCommand()); + h.setEnvironment(GitRebaseEditorMain.IDEA_REBASE_HANDER_NO, Integer.toString(editorNo)); + } + + /** + * The internal xml rcp handler + */ + public class InternalHandler { + /** + * Edit commits for the rebase operation + * + * @param handlerNo the handler no + * @param path the path to edit + * @return exit code + */ + @SuppressWarnings({"UnusedDeclaration"}) + public int editCommits(int handlerNo, String path) { + GitRebaseEditorHandler editor = getHandler(handlerNo); + return editor.editCommits(path); + } } - } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseEntry.java b/plugin/src/main/java/git4idea/rebase/GitRebaseEntry.java index 59cb515..f9b251f 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseEntry.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseEntry.java @@ -15,124 +15,111 @@ */ package git4idea.rebase; -import org.jetbrains.annotations.NonNls; -import jakarta.annotation.Nonnull; import consulo.logging.Logger; +import jakarta.annotation.Nonnull; /** * The entry for rebase editor */ -class GitRebaseEntry -{ - /** - * the logger - */ - private static final Logger log = Logger.getInstance(GitRebaseEntry.class.getName()); - /** - * The commit hash - */ - private final String myCommit; - /** - * The commit comment subject line - */ - private final String mySubject; - /** - * The action associated with the entry - */ - private Action myAction; +class GitRebaseEntry { + /** + * the logger + */ + private static final Logger LOG = Logger.getInstance(GitRebaseEntry.class); + /** + * The commit hash + */ + private final String myCommit; + /** + * The commit comment subject line + */ + private final String mySubject; + /** + * The action associated with the entry + */ + private Action myAction; - /** - * The constructor - * - * @param action - * @param commit the commit hash - * @param subject the commit subject - */ - public GitRebaseEntry(String action, final String commit, final String subject) - { - myCommit = commit; - mySubject = subject; - myAction = Action.fromString(action); - } + /** + * The constructor + * + * @param action + * @param commit the commit hash + * @param subject the commit subject + */ + public GitRebaseEntry(String action, String commit, String subject) { + myCommit = commit; + mySubject = subject; + myAction = Action.fromString(action); + } - /** - * @return the commit hash - */ - public String getCommit() - { - return myCommit; - } + /** + * @return the commit hash + */ + public String getCommit() { + return myCommit; + } - /** - * @return the commit subject - */ - public String getSubject() - { - return mySubject; - } + /** + * @return the commit subject + */ + public String getSubject() { + return mySubject; + } - /** - * @return the action associated with the commit - */ - public Action getAction() - { - return myAction; - } + /** + * @return the action associated with the commit + */ + public Action getAction() { + return myAction; + } - /** - * @param action a new action to set - */ - public void setAction(final Action action) - { - if(action == null) - { - log.error("The action must not be null"); - } - else - { - myAction = action; - } - } + /** + * @param action a new action to set + */ + public void setAction(Action action) { + if (action == null) { + LOG.error("The action must not be null"); + } + else { + myAction = action; + } + } - /** - * The action associated with the commit - */ - public enum Action - { - /** - * the pick action - */ - pick, - /** - * the edit action, the user will be offered to alter commit - */ - edit, - /** - * the skip action - */ - skip, - /** - * the squash action (for two or more commits) - */ - squash, + /** + * The action associated with the commit + */ + public enum Action { + /** + * the pick action + */ + pick, + /** + * the edit action, the user will be offered to alter commit + */ + edit, + /** + * the skip action + */ + skip, + /** + * the squash action (for two or more commits) + */ + squash, - reword, + reword, - fixup; + fixup; - @Nonnull - static Action fromString(@NonNls @Nonnull String actionName) - { - try - { - return valueOf(actionName.toLowerCase()); - } - catch(IllegalArgumentException e) - { - log.error(e); - return pick; - } - } - } + @Nonnull + static Action fromString(@Nonnull String actionName) { + try { + return valueOf(actionName.toLowerCase()); + } + catch (IllegalArgumentException e) { + LOG.error(e); + return pick; + } + } + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseLineListener.java b/plugin/src/main/java/git4idea/rebase/GitRebaseLineListener.java index 29a98f4..8f7db22 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseLineListener.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseLineListener.java @@ -26,134 +26,134 @@ * This listener gathers information relevant to the progress of the rebase operation */ public class GitRebaseLineListener extends GitLineHandlerAdapter { - /** - * Git rebase progress message - */ - private static final Pattern PROGRESS = Pattern.compile("^Rebasing \\((\\d+)/(\\d+)\\)$"); - /** - * The status - */ - private Status myStatus; - /** - * The progress line - */ - private String myProgressLine; - - /** - * {@inheritDoc} - */ - @Override - public synchronized void onLineAvailable(String line, Key outputType) { - if (outputType == ProcessOutputTypes.STDOUT) { - if (PROGRESS.matcher(line).matches()) { - myProgressLine = line; - // a bit dodgy line since STDERR line could arrive before STDOUT line, - // but in practice STDOUT comes first. - myStatus = null; - } - } - else { - if (line.startsWith("You can amend the commit now")) { - assert myStatus == null; - myStatus = Status.EDIT; - } - else if (line.startsWith("Successfully rebased and updated")) { - assert myStatus == null; - myStatus = Status.FINISHED; - } - else if (line.startsWith("Automatic cherry-pick failed") || line.startsWith("When you have resolved this problem")) { - assert myStatus == null || myStatus == Status.ERROR; - myStatus = Status.CONFLICT; - } - else if (line.startsWith("Could not execute editor")) { - assert myStatus == null; - myStatus = myProgressLine == null ? Status.CANCELLED : Status.ERROR; - } - else if (line.startsWith("fatal") || line.startsWith("error: ") || line.startsWith("Cannot rebase")) { - if (myStatus != Status.CONFLICT) { - myStatus = Status.ERROR; - } - } - } - } - - /** - * @return the progress values as a pair - */ - public synchronized Result getResult() { - int total; - int current; - if (myProgressLine != null) { - // the integers already matched the digits pattern, so they should parse - final Matcher matcher = PROGRESS.matcher(myProgressLine); - if (matcher.matches()) { - current = Integer.parseInt(matcher.group(1)); - total = Integer.parseInt(matcher.group(2)); - } - else { - throw new IllegalStateException("The wrong current result line: " + myProgressLine); - } - } - else { - total = current = 0; - } - return new Result(myStatus == null ? Status.FINISHED : myStatus, total, current); - } - - /** - * The result of operation - */ - public static final class Result { /** - * The operation status + * Git rebase progress message */ - public final Status status; + private static final Pattern PROGRESS = Pattern.compile("^Rebasing \\((\\d+)/(\\d+)\\)$"); /** - * The total number of commits + * The status */ - public final int total; + private Status myStatus; /** - * The commit number that is being currently processed + * The progress line */ - public final int current; + private String myProgressLine; /** - * A constructor - * - * @param status the status - * @param total the commit count - * @param current the current commit + * {@inheritDoc} */ - public Result(Status status, int total, int current) { - this.status = status; - this.total = total; - this.current = current; + @Override + public synchronized void onLineAvailable(String line, Key outputType) { + if (outputType == ProcessOutputTypes.STDOUT) { + if (PROGRESS.matcher(line).matches()) { + myProgressLine = line; + // a bit dodgy line since STDERR line could arrive before STDOUT line, + // but in practice STDOUT comes first. + myStatus = null; + } + } + else { + if (line.startsWith("You can amend the commit now")) { + assert myStatus == null; + myStatus = Status.EDIT; + } + else if (line.startsWith("Successfully rebased and updated")) { + assert myStatus == null; + myStatus = Status.FINISHED; + } + else if (line.startsWith("Automatic cherry-pick failed") || line.startsWith("When you have resolved this problem")) { + assert myStatus == null || myStatus == Status.ERROR; + myStatus = Status.CONFLICT; + } + else if (line.startsWith("Could not execute editor")) { + assert myStatus == null; + myStatus = myProgressLine == null ? Status.CANCELLED : Status.ERROR; + } + else if (line.startsWith("fatal") || line.startsWith("error: ") || line.startsWith("Cannot rebase")) { + if (myStatus != Status.CONFLICT) { + myStatus = Status.ERROR; + } + } + } } - } - /** - * The current rebase status - */ - public enum Status { - /** - * Rebase operation is cancelled (could not execute editor) - */ - CANCELLED, /** - * Rebase is finished + * @return the progress values as a pair */ - FINISHED, - /** - * Suspended for edit - */ - EDIT, + public synchronized Result getResult() { + int total; + int current; + if (myProgressLine != null) { + // the integers already matched the digits pattern, so they should parse + Matcher matcher = PROGRESS.matcher(myProgressLine); + if (matcher.matches()) { + current = Integer.parseInt(matcher.group(1)); + total = Integer.parseInt(matcher.group(2)); + } + else { + throw new IllegalStateException("The wrong current result line: " + myProgressLine); + } + } + else { + total = current = 0; + } + return new Result(myStatus == null ? Status.FINISHED : myStatus, total, current); + } + /** - * Suspended due to the conflict + * The result of operation */ - CONFLICT, + public static final class Result { + /** + * The operation status + */ + public final Status status; + /** + * The total number of commits + */ + public final int total; + /** + * The commit number that is being currently processed + */ + public final int current; + + /** + * A constructor + * + * @param status the status + * @param total the commit count + * @param current the current commit + */ + public Result(Status status, int total, int current) { + this.status = status; + this.total = total; + this.current = current; + } + } + /** - * Suspended due to the error + * The current rebase status */ - ERROR - } + public enum Status { + /** + * Rebase operation is cancelled (could not execute editor) + */ + CANCELLED, + /** + * Rebase is finished + */ + FINISHED, + /** + * Suspended for edit + */ + EDIT, + /** + * Suspended due to the conflict + */ + CONFLICT, + /** + * Suspended due to the error + */ + ERROR + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseProblemDetector.java b/plugin/src/main/java/git4idea/rebase/GitRebaseProblemDetector.java index e4f7489..75bf688 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseProblemDetector.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseProblemDetector.java @@ -32,77 +32,65 @@ * To use the detector add it as a {@link GitLineHandlerListener} to {@link GitLineHandler} *

*/ -public class GitRebaseProblemDetector extends GitLineHandlerAdapter -{ - private final static String[] REBASE_CONFLICT_INDICATORS = { - "Merge conflict in", - "hint: after resolving the conflicts, mark the corrected paths", - "You must edit all merge conflicts", - "Failed to merge in the changes", - "could not apply" - }; - private static final String REBASE_NO_CHANGE_INDICATOR = "No changes - did you forget to use 'git add'?"; - private static final String[] DIRTY_TREE_INDICATORS = { - "you have unstaged changes", - "your index contains uncommitted changes" - }; - private static final String STOPPED_FOR_EDITING = "You can amend the commit now"; +public class GitRebaseProblemDetector extends GitLineHandlerAdapter { + private final static String[] REBASE_CONFLICT_INDICATORS = { + "Merge conflict in", + "hint: after resolving the conflicts, mark the corrected paths", + "You must edit all merge conflicts", + "Failed to merge in the changes", + "could not apply" + }; + private static final String REBASE_NO_CHANGE_INDICATOR = "No changes - did you forget to use 'git add'?"; + private static final String[] DIRTY_TREE_INDICATORS = { + "you have unstaged changes", + "your index contains uncommitted changes" + }; + private static final String STOPPED_FOR_EDITING = "You can amend the commit now"; - private volatile boolean myMergeConflict; - private volatile boolean myNoChangeError; - private volatile boolean myDirtyTree; - private volatile boolean myStoppedForEditing; + private volatile boolean myMergeConflict; + private volatile boolean myNoChangeError; + private volatile boolean myDirtyTree; + private volatile boolean myStoppedForEditing; - public boolean isNoChangeError() - { - return myNoChangeError; - } + public boolean isNoChangeError() { + return myNoChangeError; + } - public boolean isMergeConflict() - { - return myMergeConflict; - } + public boolean isMergeConflict() { + return myMergeConflict; + } - public boolean isDirtyTree() - { - return myDirtyTree; - } + public boolean isDirtyTree() { + return myDirtyTree; + } - public boolean hasStoppedForEditing() - { - return myStoppedForEditing; - } + public boolean hasStoppedForEditing() { + return myStoppedForEditing; + } - @Override - public void onLineAvailable(String line, Key outputType) - { - for(String conflictIndicator : REBASE_CONFLICT_INDICATORS) - { - if(StringUtil.containsIgnoreCase(line, conflictIndicator)) - { - myMergeConflict = true; - return; - } - } + @Override + public void onLineAvailable(String line, Key outputType) { + for (String conflictIndicator : REBASE_CONFLICT_INDICATORS) { + if (StringUtil.containsIgnoreCase(line, conflictIndicator)) { + myMergeConflict = true; + return; + } + } - if(StringUtil.containsIgnoreCase(line, REBASE_NO_CHANGE_INDICATOR)) - { - myNoChangeError = true; - return; - } + if (StringUtil.containsIgnoreCase(line, REBASE_NO_CHANGE_INDICATOR)) { + myNoChangeError = true; + return; + } - for(String indicator : DIRTY_TREE_INDICATORS) - { - if(StringUtil.containsIgnoreCase(line, indicator)) - { - myDirtyTree = true; - return; - } - } + for (String indicator : DIRTY_TREE_INDICATORS) { + if (StringUtil.containsIgnoreCase(line, indicator)) { + myDirtyTree = true; + return; + } + } - if(StringUtil.containsIgnoreCase(line, STOPPED_FOR_EDITING)) - { - myStoppedForEditing = true; - } - } + if (StringUtil.containsIgnoreCase(line, STOPPED_FOR_EDITING)) { + myStoppedForEditing = true; + } + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseResumeMode.java b/plugin/src/main/java/git4idea/rebase/GitRebaseResumeMode.java index 84f05ee..36503cb 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseResumeMode.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseResumeMode.java @@ -17,22 +17,19 @@ import jakarta.annotation.Nonnull; -public enum GitRebaseResumeMode -{ - CONTINUE("--continue"), - SKIP("--skip"); +public enum GitRebaseResumeMode { + CONTINUE("--continue"), + SKIP("--skip"); - @Nonnull - private final String myCommandLineArgument; + @Nonnull + private final String myCommandLineArgument; - GitRebaseResumeMode(@Nonnull String argument) - { - myCommandLineArgument = argument; - } + GitRebaseResumeMode(@Nonnull String argument) { + myCommandLineArgument = argument; + } - @Nonnull - public String asCommandLineArgument() - { - return myCommandLineArgument; - } + @Nonnull + public String asCommandLineArgument() { + return myCommandLineArgument; + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseStatus.java b/plugin/src/main/java/git4idea/rebase/GitRebaseStatus.java index 7b70593..ffd7590 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseStatus.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseStatus.java @@ -15,72 +15,64 @@ */ package git4idea.rebase; -import java.util.Collection; -import java.util.Collections; - import jakarta.annotation.Nonnull; -class GitRebaseStatus -{ +import java.util.Collection; +import java.util.Collections; - enum Type - { - /** - * Rebase has completed successfully. - */ - SUCCESS, - /** - * Rebase started, and some commits were already applied, - * but then rebase stopped because of conflicts, or to edit during interactive rebase, or because of an error.
- * Such rebase can be retried/continued by calling `git rebase --continue/--skip`, or - * it can be aborted by calling `git rebase --abort`. - */ - SUSPENDED, - /** - * Rebase started, but immediately stopped because of an error at the very beginning. - * As opposed to {@link #SUSPENDED}, no commits have been applied yet.
- * Retrying such rebase requires calling `git rebase ` again, - * there is nothing to abort. - */ - ERROR, - /** - * Rebase hasn't started yet. - */ - NOT_STARTED - } +class GitRebaseStatus { + enum Type { + /** + * Rebase has completed successfully. + */ + SUCCESS, + /** + * Rebase started, and some commits were already applied, + * but then rebase stopped because of conflicts, or to edit during interactive rebase, or because of an error.
+ * Such rebase can be retried/continued by calling `git rebase --continue/--skip`, or + * it can be aborted by calling `git rebase --abort`. + */ + SUSPENDED, + /** + * Rebase started, but immediately stopped because of an error at the very beginning. + * As opposed to {@link #SUSPENDED}, no commits have been applied yet.
+ * Retrying such rebase requires calling `git rebase ` again, + * there is nothing to abort. + */ + ERROR, + /** + * Rebase hasn't started yet. + */ + NOT_STARTED + } - @Nonnull - private final Type myType; - @Nonnull - private final Collection mySkippedCommits; + @Nonnull + private final Type myType; + @Nonnull + private final Collection mySkippedCommits; - @Nonnull - static GitRebaseStatus notStarted() - { - return new GitRebaseStatus(Type.NOT_STARTED, Collections.emptyList()); - } + @Nonnull + static GitRebaseStatus notStarted() { + return new GitRebaseStatus(Type.NOT_STARTED, Collections.emptyList()); + } - GitRebaseStatus(@Nonnull Type type, @Nonnull Collection skippedCommits) - { - myType = type; - mySkippedCommits = skippedCommits; - } + GitRebaseStatus(@Nonnull Type type, @Nonnull Collection skippedCommits) { + myType = type; + mySkippedCommits = skippedCommits; + } - @Nonnull - Collection getSkippedCommits() - { - return mySkippedCommits; - } + @Nonnull + Collection getSkippedCommits() { + return mySkippedCommits; + } - @Nonnull - Type getType() - { - return myType; - } + @Nonnull + Type getType() { + return myType; + } - @Override - public String toString() - { - return myType.toString(); - } + @Override + public String toString() { + return myType.toString(); + } } diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseUnstructuredEditor.java b/plugin/src/main/java/git4idea/rebase/GitRebaseUnstructuredEditor.java index ab738e4..871cf79 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseUnstructuredEditor.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseUnstructuredEditor.java @@ -22,12 +22,12 @@ import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; import consulo.ui.ex.awt.JBScrollPane; +import consulo.ui.ex.awt.JBUI; import consulo.util.io.FileUtil; import consulo.virtualFileSystem.VirtualFile; import git4idea.config.GitConfigUtil; import javax.swing.*; -import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -123,7 +123,7 @@ public JComponent getPreferredFocusedComponent() { */ private void $$$setupUI$$$() { myPanel = new JPanel(); - myPanel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1)); + myPanel.setLayout(new GridLayoutManager(3, 2, JBUI.emptyInsets(), -1, -1)); JLabel label1 = new JLabel(); $$$loadLabelText$$$(label1, GitLocalize.rebaseUnstructuredEditorMessage().get()); myPanel.add( diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaseUtils.java b/plugin/src/main/java/git4idea/rebase/GitRebaseUtils.java index 4c99efa..c54292f 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaseUtils.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaseUtils.java @@ -52,7 +52,7 @@ public class GitRebaseUtils { /** * The logger instance */ - private final static Logger LOG = Logger.getInstance(GitRebaseUtils.class.getName()); + private final static Logger LOG = Logger.getInstance(GitRebaseUtils.class); /** * A private constructor for utility class diff --git a/plugin/src/main/java/git4idea/rebase/GitRebaser.java b/plugin/src/main/java/git4idea/rebase/GitRebaser.java index 5b1e58f..984d309 100644 --- a/plugin/src/main/java/git4idea/rebase/GitRebaser.java +++ b/plugin/src/main/java/git4idea/rebase/GitRebaser.java @@ -364,12 +364,14 @@ public TrivialEditor( } @Override + @RequiredUIAccess public int editCommits(String path) { return 0; } } @Nonnull + @RequiredUIAccess public GitUpdateResult handleRebaseFailure( @Nonnull GitLineHandler handler, @Nonnull VirtualFile root, @@ -479,6 +481,7 @@ public PushRebaseEditor( } @Override + @RequiredUIAccess public int editCommits(String path) { if (!myRebaseEditorShown) { myRebaseEditorShown = true; diff --git a/plugin/src/main/java/git4idea/rebase/GitSuccessfulRebase.java b/plugin/src/main/java/git4idea/rebase/GitSuccessfulRebase.java index 5107050..2bee1b2 100644 --- a/plugin/src/main/java/git4idea/rebase/GitSuccessfulRebase.java +++ b/plugin/src/main/java/git4idea/rebase/GitSuccessfulRebase.java @@ -16,105 +16,87 @@ package git4idea.rebase; import consulo.util.lang.StringUtil; +import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; import java.util.Collection; import java.util.List; -import jakarta.annotation.Nonnull; -import jakarta.annotation.Nullable; - -class GitSuccessfulRebase extends GitRebaseStatus -{ - private final SuccessType mySuccessType; +class GitSuccessfulRebase extends GitRebaseStatus { + private final SuccessType mySuccessType; - private GitSuccessfulRebase(@Nonnull SuccessType successType, @Nonnull Collection skippedCommits) - { - super(Type.SUCCESS, skippedCommits); - mySuccessType = successType; - } + private GitSuccessfulRebase(@Nonnull SuccessType successType, @Nonnull Collection skippedCommits) { + super(Type.SUCCESS, skippedCommits); + mySuccessType = successType; + } - @Nonnull - public SuccessType getSuccessType() - { - return mySuccessType; - } + @Nonnull + public SuccessType getSuccessType() { + return mySuccessType; + } - @Nonnull - static GitSuccessfulRebase parseFromOutput(@Nonnull List output, @Nonnull Collection skippedCommits) - { - return new GitSuccessfulRebase(SuccessType.fromOutput(output), skippedCommits); - } + @Nonnull + static GitSuccessfulRebase parseFromOutput( + @Nonnull List output, + @Nonnull Collection skippedCommits + ) { + return new GitSuccessfulRebase(SuccessType.fromOutput(output), skippedCommits); + } - enum SuccessType - { - REBASED - { - @Nonnull - @Override - public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) - { - if(withCheckout) - { - return "Checked out" + mention(currentBranch) + " and rebased it on " + baseBranch; - } - else - { - return "Rebased" + mention(currentBranch) + " on " + baseBranch; - } - } - }, - UP_TO_DATE - { - @Nonnull - @Override - public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) - { - String msg = currentBranch != null ? currentBranch + " is up-to-date" : "Up-to-date"; - msg += " with " + baseBranch; - return msg; - } - }, - FAST_FORWARDED - { - @Nonnull - @Override - public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) - { - if(withCheckout) - { - return "Checked out" + mention(currentBranch) + " and fast-forwarded it to " + baseBranch; - } - else - { - return "Fast-forwarded" + mention(currentBranch) + " to " + baseBranch; - } - } - }; + enum SuccessType { + REBASED { + @Nonnull + @Override + public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) { + if (withCheckout) { + return "Checked out" + mention(currentBranch) + " and rebased it on " + baseBranch; + } + else { + return "Rebased" + mention(currentBranch) + " on " + baseBranch; + } + } + }, + UP_TO_DATE { + @Nonnull + @Override + public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) { + String msg = currentBranch != null ? currentBranch + " is up-to-date" : "Up-to-date"; + msg += " with " + baseBranch; + return msg; + } + }, + FAST_FORWARDED { + @Nonnull + @Override + public String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout) { + if (withCheckout) { + return "Checked out" + mention(currentBranch) + " and fast-forwarded it to " + baseBranch; + } + else { + return "Fast-forwarded" + mention(currentBranch) + " to " + baseBranch; + } + } + }; - @Nonnull - private static String mention(@Nullable String currentBranch) - { - return currentBranch != null ? " " + currentBranch : ""; - } + @Nonnull + private static String mention(@Nullable String currentBranch) { + return currentBranch != null ? " " + currentBranch : ""; + } - @Nonnull - abstract String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout); + @Nonnull + abstract String formatMessage(@Nullable String currentBranch, @Nonnull String baseBranch, boolean withCheckout); - @Nonnull - public static SuccessType fromOutput(@Nonnull List output) - { - for(String line : output) - { - if(StringUtil.containsIgnoreCase(line, "Fast-forwarded")) - { - return FAST_FORWARDED; - } - if(StringUtil.containsIgnoreCase(line, "is up to date")) - { - return UP_TO_DATE; - } - } - return REBASED; - } - } + @Nonnull + public static SuccessType fromOutput(@Nonnull List output) { + for (String line : output) { + if (StringUtil.containsIgnoreCase(line, "Fast-forwarded")) { + return FAST_FORWARDED; + } + if (StringUtil.containsIgnoreCase(line, "is up to date")) { + return UP_TO_DATE; + } + } + return REBASED; + } + } } diff --git a/plugin/src/main/java/git4idea/repo/GitBranchTrackInfo.java b/plugin/src/main/java/git4idea/repo/GitBranchTrackInfo.java index 64aa043..3fb9a99 100644 --- a/plugin/src/main/java/git4idea/repo/GitBranchTrackInfo.java +++ b/plugin/src/main/java/git4idea/repo/GitBranchTrackInfo.java @@ -23,11 +23,23 @@ * @author Kirill Likhodedov */ public record GitBranchTrackInfo(@Nonnull GitLocalBranch localBranch, @Nonnull GitRemoteBranch remoteBranch, boolean merge) { + @Deprecated + @Nonnull + public GitLocalBranch getLocalBranch() { + return localBranch(); + } + @Nonnull public GitRemote getRemote() { return remoteBranch.getRemote(); } + @Deprecated + @Nonnull + public GitRemoteBranch getRemoteBranch() { + return remoteBranch(); + } + @Override public String toString() { return String.format("%s->%s", localBranch.getName(), remoteBranch.getName()); diff --git a/plugin/src/main/java/git4idea/repo/GitHooksInfo.java b/plugin/src/main/java/git4idea/repo/GitHooksInfo.java index 4866b37..cf4ce3e 100644 --- a/plugin/src/main/java/git4idea/repo/GitHooksInfo.java +++ b/plugin/src/main/java/git4idea/repo/GitHooksInfo.java @@ -1,4 +1,4 @@ package git4idea.repo; -public record GitHooksInfo(boolean preCommitHookAvailable, boolean prePushHookAvailable) { +public record GitHooksInfo(boolean isPreCommitHookAvailable, boolean isPrePushHookAvailable) { } diff --git a/plugin/src/main/java/git4idea/repo/GitRepoInfo.java b/plugin/src/main/java/git4idea/repo/GitRepoInfo.java index 322bf4b..74eb881 100644 --- a/plugin/src/main/java/git4idea/repo/GitRepoInfo.java +++ b/plugin/src/main/java/git4idea/repo/GitRepoInfo.java @@ -41,11 +41,66 @@ public record GitRepoInfo( @Nonnull Collection submodules, @Nonnull GitHooksInfo hooksInfo ) { + @Deprecated @Nullable public GitLocalBranch getCurrentBranch() { return currentBranch(); } + @Deprecated + @Nonnull + public Collection getRemotes() { + return remotes(); + } + + @Deprecated + @Nonnull + public Map getLocalBranchesWithHashes() { + return localBranches(); + } + + @Deprecated + @Nonnull + public Map getRemoteBranchesWithHashes() { + return remoteBranches(); + } + + @Deprecated + @Nonnull + public Collection getRemoteBranches() { + return remoteBranches().keySet(); + } + + @Deprecated + @Nonnull + public Collection getBranchTrackInfos() { + return branchTrackInfos(); + } + + @Deprecated + @Nullable + public String getCurrentRevision() { + return currentRevision(); + } + + @Deprecated + @Nonnull + public Repository.State getState() { + return state(); + } + + @Deprecated + @Nonnull + public Collection getSubmodules() { + return submodules(); + } + + @Deprecated + @Nonnull + public GitHooksInfo getHooksInfo() { + return hooksInfo(); + } + @Override public boolean equals(Object o) { //noinspection SimplifiableIfStatement diff --git a/plugin/src/main/java/git4idea/repo/GitSubmoduleInfo.java b/plugin/src/main/java/git4idea/repo/GitSubmoduleInfo.java index 307a57d..7627fb5 100644 --- a/plugin/src/main/java/git4idea/repo/GitSubmoduleInfo.java +++ b/plugin/src/main/java/git4idea/repo/GitSubmoduleInfo.java @@ -3,4 +3,15 @@ import jakarta.annotation.Nonnull; public record GitSubmoduleInfo(@Nonnull String path, @Nonnull String url) { + @Deprecated + @Nonnull + public String getPath() { + return path(); + } + + @Deprecated + @Nonnull + public String getUrl() { + return url(); + } } diff --git a/plugin/src/main/java/git4idea/ui/GitResetDialog.form b/plugin/src/main/java/git4idea/ui/GitResetDialog.form deleted file mode 100644 index 1b23207..0000000 --- a/plugin/src/main/java/git4idea/ui/GitResetDialog.form +++ /dev/null @@ -1,122 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/ui/GitResetDialog.java b/plugin/src/main/java/git4idea/ui/GitResetDialog.java index 2610f47..f78dfa0 100644 --- a/plugin/src/main/java/git4idea/ui/GitResetDialog.java +++ b/plugin/src/main/java/git4idea/ui/GitResetDialog.java @@ -15,16 +15,20 @@ */ package git4idea.ui; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; import consulo.git.localize.GitLocalize; import consulo.project.Project; import consulo.ui.ex.awt.DialogWrapper; -import consulo.ui.ex.awt.SimpleListCellRenderer; +import consulo.ui.ex.awt.JBUI; import consulo.virtualFileSystem.VirtualFile; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; import git4idea.util.GitUIUtil; import javax.swing.*; +import java.awt.*; import java.util.List; /** @@ -72,7 +76,7 @@ public class GitResetDialog extends DialogWrapper { * @param roots the list of the roots * @param defaultRoot the default root to select */ - public GitResetDialog(final Project project, final List roots, final VirtualFile defaultRoot) { + public GitResetDialog(Project project, List roots, VirtualFile defaultRoot) { super(project, true); myProject = project; setTitle(GitLocalize.resetTitle()); @@ -107,9 +111,9 @@ void validateFields() { */ public GitLineHandler handler() { GitLineHandler handler = new GitLineHandler(myProject, getGitRoot(), GitCommand.RESET); - GitResetType resetType = (GitResetType)myResetTypeComboBox.getSelectedItem(); + GitResetType resetType = (GitResetType) myResetTypeComboBox.getSelectedItem(); resetType.addParametersTo(handler); - final String commit = myCommitTextField.getText().trim(); + String commit = myCommitTextField.getText().trim(); if (commit.length() != 0) { handler.addParameters(commit); } @@ -121,7 +125,7 @@ public GitLineHandler handler() { * @return the selected git root */ public VirtualFile getGitRoot() { - return (VirtualFile)myGitRootComboBox.getSelectedItem(); + return (VirtualFile) myGitRootComboBox.getSelectedItem(); } /** @@ -147,4 +151,340 @@ protected String getDimensionServiceKey() { protected String getHelpId() { return "gitResetHead"; } + + { +// GUI initializer generated by Consulo GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + myPanel = new JPanel(); + myPanel.setLayout(new GridLayoutManager(5, 2, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.commonGitRoot().get()); + myPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + myPanel.add( + spacer1, + new GridConstraints( + 4, + 0, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_VERTICAL, + 1, + GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.commonCurrentBranch().get()); + myPanel.add( + label2, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myCurrentBranchLabel = new JLabel(); + myCurrentBranchLabel.setText(""); + myCurrentBranchLabel.setToolTipText(GitLocalize.commonCurrentBranchTooltip().get()); + myPanel.add( + myCurrentBranchLabel, + new GridConstraints( + 1, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label3 = new JLabel(); + this.$$$loadLabelText$$$(label3, GitLocalize.resetType().get()); + myPanel.add( + label3, + new GridConstraints( + 2, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myGitRootComboBox = new JComboBox(); + myGitRootComboBox.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myPanel.add( + myGitRootComboBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel1 = new JPanel(); + panel1.setLayout(new GridLayoutManager(1, 2, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel1, + new GridConstraints( + 2, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myResetTypeComboBox = new JComboBox<>(); + myResetTypeComboBox.setToolTipText(GitLocalize.resetTypeTooltip().get()); + panel1.add( + myResetTypeComboBox, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer2 = new Spacer(); + panel1.add( + spacer2, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + 1, + null, + null, + null, + 0, + false + ) + ); + JLabel label4 = new JLabel(); + this.$$$loadLabelText$$$(label4, GitLocalize.resetCommitLabel().get()); + myPanel.add( + label4, + new GridConstraints( + 3, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JPanel panel2 = new JPanel(); + panel2.setLayout(new GridLayoutManager(1, 2, JBUI.emptyInsets(), -1, -1)); + myPanel.add( + panel2, + new GridConstraints( + 3, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_BOTH, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + null, + null, + null, + 0, + false + ) + ); + myCommitTextField = new JTextField(); + myCommitTextField.setText("HEAD"); + myCommitTextField.setToolTipText(GitLocalize.resetCommitTooltip().get()); + panel2.add( + myCommitTextField, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + new Dimension(150, -1), + null, + 0, + false + ) + ); + myValidateButton = new JButton(); + this.$$$loadButtonText$$$(myValidateButton, GitLocalize.resetValidate().get()); + panel2.add( + myValidateButton, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + label1.setLabelFor(myGitRootComboBox); + label3.setLabelFor(myResetTypeComboBox); + label4.setLabelFor(myCommitTextField); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myPanel; + } } diff --git a/plugin/src/main/java/git4idea/ui/GitStashDialog.form b/plugin/src/main/java/git4idea/ui/GitStashDialog.form deleted file mode 100644 index 7bf0b8e..0000000 --- a/plugin/src/main/java/git4idea/ui/GitStashDialog.form +++ /dev/null @@ -1,80 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/plugin/src/main/java/git4idea/ui/GitStashDialog.java b/plugin/src/main/java/git4idea/ui/GitStashDialog.java index 1dc168f..d901741 100644 --- a/plugin/src/main/java/git4idea/ui/GitStashDialog.java +++ b/plugin/src/main/java/git4idea/ui/GitStashDialog.java @@ -15,16 +15,21 @@ */ package git4idea.ui; +import com.intellij.uiDesigner.core.GridConstraints; +import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.uiDesigner.core.Spacer; import consulo.git.localize.GitLocalize; import consulo.project.Project; import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.DialogWrapper; +import consulo.ui.ex.awt.JBUI; import consulo.virtualFileSystem.VirtualFile; import git4idea.commands.GitCommand; import git4idea.commands.GitLineHandler; import git4idea.util.GitUIUtil; import javax.swing.*; +import java.awt.*; import java.util.List; /** @@ -45,7 +50,7 @@ public class GitStashDialog extends DialogWrapper { * @param roots the list of Git roots * @param defaultRoot the default root to select */ - public GitStashDialog(final Project project, final List roots, final VirtualFile defaultRoot) { + public GitStashDialog(Project project, List roots, VirtualFile defaultRoot) { super(project, true); myProject = project; setTitle(GitLocalize.stashTitle()); @@ -60,7 +65,7 @@ public GitLineHandler handler() { if (myKeepIndexCheckBox.isSelected()) { handler.addParameters("--keep-index"); } - final String msg = myMessageTextField.getText().trim(); + String msg = myMessageTextField.getText().trim(); if (msg.length() != 0) { handler.addParameters(msg); } @@ -71,7 +76,7 @@ public GitLineHandler handler() { * @return the selected git root */ public VirtualFile getGitRoot() { - return (VirtualFile)myGitRootComboBox.getSelectedItem(); + return (VirtualFile) myGitRootComboBox.getSelectedItem(); } @Override @@ -94,4 +99,240 @@ protected String getHelpId() { public JComponent getPreferredFocusedComponent() { return myMessageTextField; } + + { +// GUI initializer generated by Consulo GUI Designer +// >>> IMPORTANT!! <<< +// DO NOT EDIT OR ADD ANY CODE HERE! + $$$setupUI$$$(); + } + + /** + * Method generated by Consulo GUI Designer + * >>> IMPORTANT!! <<< + * DO NOT edit this method OR call it in your code! + */ + private void $$$setupUI$$$() { + myRootPanel = new JPanel(); + myRootPanel.setLayout(new GridLayoutManager(5, 2, JBUI.emptyInsets(), -1, -1)); + JLabel label1 = new JLabel(); + this.$$$loadLabelText$$$(label1, GitLocalize.commonGitRoot().get()); + myRootPanel.add( + label1, + new GridConstraints( + 0, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + Spacer spacer1 = new Spacer(); + myRootPanel.add( + spacer1, + new GridConstraints( + 4, + 0, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_VERTICAL, + 1, + GridConstraints.SIZEPOLICY_WANT_GROW, + null, + null, + null, + 0, + false + ) + ); + myGitRootComboBox = new JComboBox(); + myGitRootComboBox.setToolTipText(GitLocalize.commonGitRootTooltip().get()); + myRootPanel.add( + myGitRootComboBox, + new GridConstraints( + 0, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label2 = new JLabel(); + this.$$$loadLabelText$$$(label2, GitLocalize.commonCurrentBranch().get()); + myRootPanel.add( + label2, + new GridConstraints( + 1, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myCurrentBranch = new JLabel(); + myCurrentBranch.setText(""); + myCurrentBranch.setToolTipText(GitLocalize.commonCurrentBranchTooltip().get()); + myRootPanel.add( + myCurrentBranch, + new GridConstraints( + 1, + 1, + 1, + 1, + GridConstraints.ANCHOR_CENTER, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + JLabel label3 = new JLabel(); + this.$$$loadLabelText$$$(label3, GitLocalize.stashMessage().get()); + myRootPanel.add( + label3, + new GridConstraints( + 2, + 0, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_FIXED, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + myMessageTextField = new JTextField(); + myMessageTextField.setToolTipText(GitLocalize.stashMessageTooltip().get()); + myRootPanel.add( + myMessageTextField, + new GridConstraints( + 2, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_WANT_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + new Dimension(150, -1), + null, + 0, + false + ) + ); + myKeepIndexCheckBox = new JCheckBox(); + this.$$$loadButtonText$$$(myKeepIndexCheckBox, GitLocalize.stashKeepIndex().get()); + myKeepIndexCheckBox.setToolTipText(GitLocalize.stashKeepIndexTooltip().get()); + myRootPanel.add( + myKeepIndexCheckBox, + new GridConstraints( + 3, + 1, + 1, + 1, + GridConstraints.ANCHOR_WEST, + GridConstraints.FILL_NONE, + GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, + GridConstraints.SIZEPOLICY_FIXED, + null, + null, + null, + 0, + false + ) + ); + label1.setLabelFor(myGitRootComboBox); + label3.setLabelFor(myMessageTextField); + } + + private void $$$loadLabelText$$$(JLabel component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setDisplayedMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + private void $$$loadButtonText$$$(AbstractButton component, String text) { + StringBuilder result = new StringBuilder(); + boolean haveMnemonic = false; + char mnemonic = '\0'; + int mnemonicIndex = -1; + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '&') { + i++; + if (i == text.length()) { + break; + } + if (!haveMnemonic && text.charAt(i) != '&') { + haveMnemonic = true; + mnemonic = text.charAt(i); + mnemonicIndex = result.length(); + } + } + result.append(text.charAt(i)); + } + component.setText(result.toString()); + if (haveMnemonic) { + component.setMnemonic(mnemonic); + component.setDisplayedMnemonicIndex(mnemonicIndex); + } + } + + public JComponent $$$getRootComponent$$$() { + return myRootPanel; + } } diff --git a/plugin/src/main/java/module-info.java b/plugin/src/main/java/module-info.java index 183a021..1480cc2 100644 --- a/plugin/src/main/java/module-info.java +++ b/plugin/src/main/java/module-info.java @@ -9,6 +9,7 @@ requires consulo.util.nodep; requires org.apache.commons.codec; + requires org.slf4j; requires trilead.ssh2; requires xmlrpc.client; requires xmlrpc.common;