Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

button to trigger writeVersionsLock #33

Draft
wants to merge 23 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-33.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: button to trigger writeVersionsLock
links:
- https://github.com/palantir/gradle-consistent-versions-idea-plugin/pull/33
1 change: 1 addition & 0 deletions gradle-consistent-versions-idea-plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ dependencies {
compileOnly 'org.immutables:value::annotations'
testImplementation 'org.junit.jupiter:junit-jupiter'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
}

grammarKit {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.gradle.versions.intellij;

import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder;
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode;
import com.intellij.openapi.externalSystem.task.TaskCallback;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.project.Project;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProjectRefreshUtils {
private static final Logger log = LoggerFactory.getLogger(ProjectRefreshUtils.class);

private ProjectRefreshUtils() {
// Utility class
}

public static void runWriteVersionsLock(Project project) {
String taskName = "writeVersionsLock";
if (hasBuildSrc(project)) {
runTaskThenRefresh(project, taskName);
} else {
refreshProjectWithTask(project, taskName);
}
}

private static void runTaskThenRefresh(Project project, String taskName) {
log.debug("Running task {} on project {}", taskName, project.getName());
TaskCallback callback = new TaskCallback() {
@Override
public void onSuccess() {
log.debug("Task {} successfully executed", taskName);
refreshProject(project);
}

@Override
public void onFailure() {
log.error("Task {} failed", taskName);
}
};
ExternalSystemTaskExecutionSettings settings = createExecutionSettings(project, taskName);
ExternalSystemUtil.runTask(
settings,
DefaultRunExecutor.EXECUTOR_ID,
project,
GradleConstants.SYSTEM_ID,
callback,
ProgressExecutionMode.IN_BACKGROUND_ASYNC);
}

private static ExternalSystemTaskExecutionSettings createExecutionSettings(Project project, String taskName) {
ExternalSystemTaskExecutionSettings settings = new ExternalSystemTaskExecutionSettings();
settings.setExternalProjectPath(project.getBasePath());
settings.setTaskNames(Collections.singletonList(taskName));
settings.setExternalSystemIdString(GradleConstants.SYSTEM_ID.toString());
return settings;
}

private static void refreshProjectWithTask(Project project, String taskName) {
log.debug("Refreshing project {} with task {}", project.getName(), taskName);
refreshProject(project, new ImportSpecBuilder(project, GradleConstants.SYSTEM_ID).withArguments(taskName));
}

private static void refreshProject(Project project) {
refreshProject(project, new ImportSpecBuilder(project, GradleConstants.SYSTEM_ID));
}

private static void refreshProject(Project project, ImportSpecBuilder importSpec) {
ExternalSystemUtil.refreshProject(project.getBasePath(), importSpec);
}

private static boolean hasBuildSrc(Project project) {
return Files.exists(Paths.get(project.getBasePath(), "buildSrc"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.gradle.versions.intellij;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.components.Service.Level;
import com.intellij.openapi.components.Storage;
import org.jetbrains.annotations.Nullable;

@Service(Level.APP)
@com.intellij.openapi.components.State(
name = "AppSettings",
storages = {@Storage("gcv-plugin-application-settings.xml")})
public final class VersionPropsAppSettings implements PersistentStateComponent<VersionPropsAppSettings.State> {

public static final class State {
private boolean enabled = true;

public void setEnabled(boolean enabled) {
this.enabled = enabled;
}

public boolean getEnabled() {
return this.enabled;
}
}

private State state = new State();

@Nullable
@Override
public State getState() {
return state;
}

@Override
public void loadState(State status) {
this.state = status;
}

public boolean isEnabled() {
return state.enabled;
}

public void setEnabled(boolean enabled) {
state.enabled = enabled;
}

public static VersionPropsAppSettings getInstance() {
return ApplicationManager.getApplication().getService(VersionPropsAppSettings.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.gradle.versions.intellij;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

public final class VersionPropsAppSettingsPage implements Configurable {
private JCheckBox enabledCheckbox;

private final VersionPropsAppSettings settings;

public VersionPropsAppSettingsPage() {
settings = VersionPropsAppSettings.getInstance();
}

@Nls
@Override
public String getDisplayName() {
return "Gradle Consistent Versions";
}

@Nullable
@Override
public JComponent createComponent() {
JPanel rootPanel = new JPanel();
enabledCheckbox = new JCheckBox("Enable writeVersionsLock on save");
rootPanel.add(enabledCheckbox);
return rootPanel;
}

@Override
public boolean isModified() {
return enabledCheckbox.isSelected() != settings.isEnabled();
}

@Override
public void apply() throws ConfigurationException {
settings.setEnabled(enabledCheckbox.isSelected());
}

@Override
public void reset() {
enabledCheckbox.setSelected(settings.isEnabled());
}

@Override
public void disposeUIResources() {
// No resources to dispose
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.gradle.versions.intellij;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import java.util.Optional;

public class VersionPropsCloseAction extends AnAction {

public VersionPropsCloseAction() {
super("Close");
}

@Override
public final void actionPerformed(AnActionEvent event) {
DataContext dataContext = event.getDataContext();
Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
Project project = event.getProject();

if (editor != null && project != null) {
VirtualFile file = editor.getVirtualFile();
if (file != null) {
VersionPropsToolbar.getInstance().hideToolbarForFile(file.getPath(), project, Optional.empty());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* (c) Copyright 2024 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.gradle.versions.intellij;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.toolbar.floating.FloatingToolbarComponent;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.vfs.VirtualFile;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;

public class VersionPropsDocumentListener implements DocumentListener {
private final FileEditor fileEditor;
private final Editor editor;
private final Map<String, String> originalContent;
private final Map<String, FloatingToolbarComponent> filesToolbarComponents;
private static final String FILE_NAME = "versions.props";
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

public VersionPropsDocumentListener(
FileEditor fileEditor,
Editor editor,
Map<String, String> originalContent,
Map<String, FloatingToolbarComponent> filesToolbarComponents) {
this.fileEditor = fileEditor;
this.editor = editor;
this.originalContent = originalContent;
this.filesToolbarComponents = filesToolbarComponents;
}

@Override
public void beforeDocumentChange(DocumentEvent event) {}

@Override
public final void documentChanged(DocumentEvent event) {
VirtualFile file = fileEditor.getFile();
if (file != null && FILE_NAME.equals(file.getName())) {
VersionPropsProjectSettings projectSettings =
VersionPropsProjectSettings.getInstance(Objects.requireNonNull(editor.getProject()));
VersionPropsAppSettings appSettings = VersionPropsAppSettings.getInstance();
if (!projectSettings.isEnabled() || appSettings.isEnabled()) {
scheduleUpdate(() -> updateFileUnchanged(file.getPath()));
return;
}

String currentContent = editor.getDocument().getText();

// This requires debouncing to so that the toolbar actually shows up
if (!originalContent.get(file.getPath()).equals(currentContent)) {
scheduleUpdate(() -> updateFileChanged(file.getPath()));
} else {
scheduleUpdate(() -> updateFileUnchanged(file.getPath()));
}
}
}

private void scheduleUpdate(Runnable updateTask) {
scheduler.schedule(() -> SwingUtilities.invokeLater(updateTask), 300, TimeUnit.MILLISECONDS);
}

private void updateFileChanged(String filePath) {
FloatingToolbarComponent toolbarComponent = filesToolbarComponents.get(filePath);
if (toolbarComponent != null) {
toolbarComponent.scheduleShow();
}
}

private void updateFileUnchanged(String filePath) {
FloatingToolbarComponent toolbarComponent = filesToolbarComponents.get(filePath);
if (toolbarComponent != null) {
toolbarComponent.scheduleHide();
}
}
}
Loading