Skip to content

Commit

Permalink
Merge pull request #13 from luisalves00/main
Browse files Browse the repository at this point in the history
Format all files before commit
  • Loading branch information
lipiridi committed Apr 13, 2024
2 parents b34a43a + 07b381b commit a5cebdc
Show file tree
Hide file tree
Showing 14 changed files with 169 additions and 72 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@

## [Unreleased]

### Added
- Reformat code with spotless commit checkin handler

### Changed
- Run gradle task for the entire project in sync mode

## [1.0.4] - 2023-12-11

### Changed
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ either for the current file you're working on or for the entire project.
| <kbd>Code</kbd> > <kbd>Reformat Project With Spotless</kbd> | <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>;</kbd> | <kbd>⌘Сmd</kbd>+<kbd>⌥Opt</kbd>+<kbd>⇧Shift</kbd>+<kbd>;</kbd> |

> ✔️ **Supports multi-module projects**
>
### Commit check
The plugin also offers a commit check to automatically apply Spotless formatting.

To enable this feature, navigate to `Settings` > `Version Control` > `Commit` and activate `Reformat code with Spotless`

### Settings

Expand All @@ -30,6 +35,7 @@ To access plugin settings, go to: `Settings` > `Tools` > `Spotless Applier`

![spotlessdemo](https://github.com/lipiridi/spotless-applier/assets/60580660/990e7bb9-8b75-4ca4-8973-f1fb2cf74e78)
![image](https://github.com/lipiridi/spotless-applier/assets/60580660/0d6ba567-e955-4193-b85b-f06e0541c790)
![image](https://github.com/lipiridi/spotless-applier/assets/60580660/fbd26155-c7f9-4837-9e97-d48530d0ae39)


## Install
Expand Down Expand Up @@ -63,4 +69,4 @@ See [CONTRIBUTING.md](CONTRIBUTING.md)
See [CHANGELOG.md](CHANGELOG.md)

## License
See [License](LICENSE)
See [License](LICENSE)
8 changes: 4 additions & 4 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ fun environment(key: String) = providers.environmentVariable(key)

plugins {
id("java")
id("org.jetbrains.kotlin.jvm") version "1.9.21"
id("org.jetbrains.intellij") version "1.16.1"
id("org.jetbrains.kotlin.jvm") version "1.9.23"
id("org.jetbrains.intellij") version "1.17.3"
id("org.jetbrains.changelog") version "2.2.0"
id("org.jetbrains.kotlinx.kover") version "0.7.5"
id("com.diffplug.spotless") version "6.23.3"
id("org.jetbrains.kotlinx.kover") version "0.7.6"
id("com.diffplug.spotless") version "6.25.0"
}

group = properties("pluginGroup").get()
Expand Down
13 changes: 5 additions & 8 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@ pluginName=Spotless Applier
pluginRepositoryUrl=https://github.com/lipiridi/spotless-applier

# SemVer format -> https://semver.org
pluginVersion=1.0.4
pluginVersion=1.0.5-SNAPSHOT

# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=222
pluginUntilBuild=233.*
pluginSinceBuild=241
pluginUntilBuild=

# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
platformType=IC
platformVersion=2022.2.5
platformVersion=2022.3.3

# Java language level used to compile sources and to generate the files for - Java 11 is required since 2020.3
javaVersion=17

# Gradle Releases -> https://github.com/gradle/gradle/releases
gradleVersion=8.2.1
gradleVersion=8.7

# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
kotlin.stdlib.default.dependency=false
Expand All @@ -28,6 +28,3 @@ org.gradle.configuration-cache=true

# Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
org.gradle.caching=true

# Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment
systemProp.org.gradle.unsafe.kotlin.assignment=true
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
17 changes: 9 additions & 8 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -144,15 +145,15 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,39 @@

import com.github.lipiridi.spotless.applier.enums.BuildTool;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import java.nio.file.Path;

public record ModuleInfo(Module module, String path, BuildTool buildTool, boolean rootModule) {}
public record ModuleInfo(Module module, String path, BuildTool buildTool, boolean rootModule) {

@SuppressWarnings("DataFlowIssue")
public static ModuleInfo create(Project project, String projectBasePath, Module module) {
BuildTool buildTool = BuildTool.resolveBuildTool(module);
if (buildTool == null) {
return null;
}

String modulePath = buildTool.getModulePath(module);
if (modulePath == null) {
return null;
}

boolean isRootModule = modulePath.equals(projectBasePath);

Module rootModule =
switch (buildTool) {
case MAVEN -> module;
case GRADLE -> {
// Gradle defines main and test folders also as modules,
// but we want to find only root module
VirtualFile moduleVirtualFile = VfsUtil.findFile(Path.of(modulePath), true);
yield ModuleUtil.findModuleForFile(moduleVirtualFile, project);
}
};

return new ModuleInfo(rootModule, modulePath, buildTool, isRootModule);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.util.GradleConstants;

public final class ToolEnvExternalSystemUtil {
private static final Logger LOG = Logger.getInstance(ToolEnvExternalSystemUtil.class);
Expand Down Expand Up @@ -53,22 +52,15 @@ public static void runTask(

final String title = moduleName + " " + taskSettings.getTaskNames();

Task task = getTask(project, document, title, taskUnderProgress, externalSystemId);
Task task = getTask(project, document, title, taskUnderProgress);

task.queue();
}

@NotNull private static Task getTask(
@NotNull Project project,
Document document,
String title,
TaskUnderProgress taskUnderProgress,
ProjectSystemId externalSystemId) {
// Currently not found the way to run gradle task synchronously
// https://intellij-support.jetbrains.com/hc/en-us/community/posts/12849664786322-Execute-Gradle-task-in-ProgressExecutionMode-MODAL-SYNC
// https://youtrack.jetbrains.com/issue/IDEA-327879
if (document == null && !externalSystemId.equals(GradleConstants.SYSTEM_ID)) {
return new Task.Modal(project, title, false) {
@NotNull Project project, Document document, String title, TaskUnderProgress taskUnderProgress) {
if (document == null) {
return new Task.Modal(project, title, true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
taskUnderProgress.execute(indicator);
Expand All @@ -78,9 +70,7 @@ public void run(@NotNull ProgressIndicator indicator) {
return new Task.Backgroundable(project, title) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
if (document != null) {
document.setReadOnly(true);
}
document.setReadOnly(true);
taskUnderProgress.execute(indicator);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@

import com.github.lipiridi.spotless.applier.ModuleInfo;
import com.github.lipiridi.spotless.applier.ReformatProcessor;
import com.github.lipiridi.spotless.applier.enums.BuildTool;
import com.github.lipiridi.spotless.applier.ui.SelectModuleDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -76,42 +71,14 @@ private Map<String, ModuleInfo> findAvailableModules(Project project) {
String projectBasePath = project.getBasePath();

return Arrays.stream(modules)
.map(module -> buildModuleInfo(project, projectBasePath, module))
.map(module -> ModuleInfo.create(project, projectBasePath, module))
.filter(Objects::nonNull)
.collect(Collectors.toMap(
moduleInfo -> moduleInfo.module().getName(),
Function.identity(),
(existing, replacement) -> existing));
}

@SuppressWarnings("DataFlowIssue")
private ModuleInfo buildModuleInfo(Project project, String projectBasePath, Module module) {
BuildTool buildTool = BuildTool.resolveBuildTool(module);
if (buildTool == null) {
return null;
}

String modulePath = buildTool.getModulePath(module);
if (modulePath == null) {
return null;
}

boolean isRootModule = modulePath.equals(projectBasePath);

Module rootModule =
switch (buildTool) {
case MAVEN -> module;
case GRADLE -> {
// Gradle defines main and test folders also as modules,
// but we want to find only root module
VirtualFile moduleVirtualFile = VfsUtil.findFile(Path.of(modulePath), true);
yield ModuleUtil.findModuleForFile(moduleVirtualFile, project);
}
};

return new ModuleInfo(rootModule, modulePath, buildTool, isRootModule);
}

private void reformatModule(Project project, ModuleInfo moduleInfo) {
new ReformatProcessor(project, moduleInfo).run();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.github.lipiridi.spotless.applier.trigger;

import com.github.lipiridi.spotless.applier.ModuleInfo;
import com.github.lipiridi.spotless.applier.ReformatProcessor;
import com.github.lipiridi.spotless.applier.ui.settings.SpotlessApplierSettingsState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.util.PairConsumer;
import java.awt.*;
import java.util.Arrays;
import java.util.Objects;
import javax.swing.*;
import org.jetbrains.annotations.Nullable;

public class SpotlessCheckinHandler extends CheckinHandler {
private static final Logger LOGGER = Logger.getInstance(SpotlessCheckinHandler.class);
private final SpotlessApplierSettingsState spotlessSettings = SpotlessApplierSettingsState.getInstance();
private final Project project;

public SpotlessCheckinHandler(Project project) {
this.project = project;
}

@Override
@Nullable public RefreshableOnComponent getBeforeCheckinConfigurationPanel() {
return new BooleanCommitOption(
project,
"Reformat code with Spotless",
true,
() -> spotlessSettings.preCommitSpotlessFormating,
(val) -> spotlessSettings.preCommitSpotlessFormating = val)
.withCheckinHandler(this);
}

@Override
public ReturnResult beforeCheckin(
@Nullable CommitExecutor executor, PairConsumer<Object, Object> additionalDataConsumer) {
if (!spotlessSettings.preCommitSpotlessFormating) {
return ReturnResult.COMMIT;
}

try {
new ReformatProcessor(project, findRootModule()).run();
return ReturnResult.COMMIT;
} catch (Exception e) {
handleError(e);
return ReturnResult.CANCEL;
}
}

private ModuleInfo findRootModule() {
Module[] modules = ProjectUtil.getModules(project);
String projectBasePath = project.getBasePath();

return Arrays.stream(modules)
.map(module -> ModuleInfo.create(project, projectBasePath, module))
.filter(Objects::nonNull)
.filter(ModuleInfo::rootModule)
.findFirst()
.orElse(null);
}

private void handleError(Exception e) {
var msg = "Error while reformatting code with Spotless";
if (e.getMessage() != null) {
msg = msg + ": " + e.getMessage();
}
LOGGER.info(msg, e);
Messages.showErrorDialog(project, msg, "Error Reformatting Code with Spotless");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.github.lipiridi.spotless.applier.trigger;

import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.changes.CommitContext;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory;
import org.jetbrains.annotations.NotNull;

public class SpotlessCheckinHandlerFactory extends CheckinHandlerFactory {

@NotNull @Override
public CheckinHandler createHandler(@NotNull CheckinProjectPanel panel, @NotNull CommitContext commitContext) {
var project = panel.getProject();
return new SpotlessCheckinHandler(project);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public final class SpotlessApplierSettingsState implements PersistentStateCompon
public boolean allowGradleCache;
public boolean optimizeImportsBeforeApplying;
public boolean prohibitImportsWithAsterisk;
public boolean preCommitSpotlessFormating;

public static SpotlessApplierSettingsState getInstance() {
return ApplicationManager.getApplication().getService(SpotlessApplierSettingsState.class);
Expand Down
Loading

0 comments on commit a5cebdc

Please sign in to comment.