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

gradle implementation for the Ark plugin #1012

Merged
merged 7 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.alipay.sofa.ark.boot.mojo;

import org.gradle.api.Plugin;
import org.gradle.api.Project;

public class ArkPlugin implements Plugin<Project> {

@Override
public void apply(Project project) {
project.getExtensions().create("arkPlugin", ArkPluginExtension.class, project);
project.getTasks().register("arkPluginJar", ArkPluginJarTask.class,
task -> {
task.setGroup("build");
task.setDescription("Generates an Ark plugin JAR file");
}
);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.alipay.sofa.ark.boot.mojo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.archivers.zip.UnixStat;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.gradle.api.internal.file.CopyActionProcessingStreamAction;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.internal.file.copy.CopyActionProcessingStream;
import org.gradle.api.internal.file.copy.FileCopyDetailsInternal;
import org.gradle.api.tasks.WorkResult;
import org.gradle.api.tasks.WorkResults;

public class ArkPluginCopyAction implements CopyAction {
private final File jarFile;

public ArkPluginCopyAction(File jarFile) {
this.jarFile = jarFile;
}

@Override
public WorkResult execute(CopyActionProcessingStream stream) {
try (ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(jarFile)) {
zipStream.setEncoding(String.valueOf(StandardCharsets.UTF_8));
Comment on lines +50 to +51
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper encoding is set without unnecessary conversions

The encoding is set using String.valueOf(StandardCharsets.UTF_8), which is unnecessary. You can directly use "UTF-8" or StandardCharsets.UTF_8.name() for clarity.

Apply this diff to simplify the encoding setting:

 try (ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(jarFile)) {
-    zipStream.setEncoding(String.valueOf(StandardCharsets.UTF_8));
+    zipStream.setEncoding(StandardCharsets.UTF_8.name());
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try (ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(jarFile)) {
zipStream.setEncoding(String.valueOf(StandardCharsets.UTF_8));
try (ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(jarFile)) {
zipStream.setEncoding(StandardCharsets.UTF_8.name());

stream.process(new StreamAction(zipStream));
return WorkResults.didWork(true);
} catch (IOException e) {
throw new RuntimeException("Failed to create JAR file", e);
}
}

private static class StreamAction implements CopyActionProcessingStreamAction {
private final ZipArchiveOutputStream zipStream;
StreamAction(ZipArchiveOutputStream zipStream) {
this.zipStream = zipStream;
}

@Override
public void processFile(FileCopyDetailsInternal details) {
try {
ZipArchiveEntry entry = createEntry(details);

if (details.isDirectory()) {
zipStream.putArchiveEntry(entry);
zipStream.closeArchiveEntry();
} else {
String path = details.getRelativePath().getPathString();

if (path.startsWith("lib")) {
setupStoredEntry(entry, details);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve path checking for 'lib' directory

Using path.startsWith("lib") may incorrectly match paths like "library/". To ensure only files in the "lib" directory are processed, check the first segment of the relative path.

Apply this diff to improve the path checking:

 String path = details.getRelativePath().getPathString();

-if (path.startsWith("lib")) {
+if (details.getRelativePath().getSegments()[0].equals("lib")) {
     setupStoredEntry(entry, details);
 }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
String path = details.getRelativePath().getPathString();
if (path.startsWith("lib")) {
setupStoredEntry(entry, details);
}
String path = details.getRelativePath().getPathString();
if (details.getRelativePath().getSegments()[0].equals("lib")) {
setupStoredEntry(entry, details);
}


zipStream.putArchiveEntry(entry);
details.copyTo(zipStream);
zipStream.closeArchiveEntry();
}
} catch (IOException e) {
throw new RuntimeException("Failed to add file to JAR: " + details.getPath(), e);
}
}
}

private static ZipArchiveEntry createEntry(FileCopyDetailsInternal details) {
String path = details.getRelativePath().getPathString();
ZipArchiveEntry entry = new ZipArchiveEntry(details.isDirectory() ? path + '/' : path);
entry.setTime(details.getLastModified());
int unixMode = details.getMode() | (details.isDirectory() ? UnixStat.DIR_FLAG : UnixStat.FILE_FLAG);
entry.setUnixMode(unixMode);
return entry;
}

private static void setupStoredEntry(ZipArchiveEntry entry, FileCopyDetailsInternal details) throws IOException {
try (InputStream inputStream = details.open()) {
CrcAndSize crcAndSize = new CrcAndSize(inputStream);
crcAndSize.setUpStoredEntry(entry);
} catch (Exception e) {
System.out.println("Warning: Unable to process JAR file in lib directory: " + details.getPath());
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a logging framework instead of System.out.println

Directly using System.out.println for logging is not advisable in production code. It is better to use a logging framework to handle log messages appropriately and consistently.

Apply this diff to replace System.out.println with a logger:

 } catch (Exception e) {
-    System.out.println("Warning: Unable to process JAR file in lib directory: " + details.getPath());
+    // Replace with appropriate logging framework
+    logger.warn("Unable to process JAR file in lib directory: {}", details.getPath(), e);
 }

Ensure you have a logger instantiated at the beginning of the class:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 public class ArkPluginCopyAction implements CopyAction {
+    private static final Logger logger = LoggerFactory.getLogger(ArkPluginCopyAction.class);

Committable suggestion was skipped due to low confidence.

}


/**
* Data holder for CRC and Size.
*/
private static class CrcAndSize {

private static final int BUFFER_SIZE = 32 * 1024;

private final CRC32 crc = new CRC32();

private long size;

CrcAndSize(InputStream inputStream) throws IOException {
try {
load(inputStream);
}
finally {
inputStream.close();
}
}

private void load(InputStream inputStream) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
this.crc.update(buffer, 0, bytesRead);
this.size += bytesRead;
}
}

void setUpStoredEntry(ZipArchiveEntry entry) {
entry.setSize(this.size);
entry.setCompressedSize(this.size);
entry.setCrc(this.crc.getValue());
entry.setMethod(ZipEntry.STORED);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.alipay.sofa.ark.boot.mojo;

import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.SetProperty;

abstract public class ArkPluginExtension {

public ArkPluginExtension(Project project){
getPriority().convention(project.provider(() -> "100"));
getOutputDirectory().convention(project.getLayout().getBuildDirectory().dir("libs"));
getPluginName().convention("sofa-ark-plugin-gradle-plugin");
getDescription().convention("ark plugin");
getActivator().convention("");
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using @Inject annotation for the constructor.

The constructor is well-structured, setting default values for various properties. However, for better integration with Gradle's dependency injection system, consider annotating the constructor with @Inject.

Apply this change to the constructor:

+import javax.inject.Inject;

abstract public class ArkPluginExtension {

+   @Inject
    public ArkPluginExtension(Project project){
        // ... (rest of the constructor remains the same)
    }
}

This change ensures that Gradle properly manages the lifecycle of this extension and provides the correct Project instance.

Committable suggestion was skipped due to low confidence.


abstract public SetProperty<String> getShades();
abstract public SetProperty<String> getExcludeArtifactIds();
abstract public SetProperty<String> getExcludeGroupIds();
abstract public SetProperty<String> getExcludes();
abstract public Property<String> getActivator();
abstract public Property<String> getPriority();
abstract public Property<String> getPluginName();

abstract public Property<String> getDescription();
abstract public DirectoryProperty getOutputDirectory();
abstract public Property<Boolean> getAttach();

private final ImportedConfig imported = new ImportedConfig();
private final ExportedConfig exported = new ExportedConfig();

public ImportedConfig getImported() {
return imported;
}

public void imported(Action<? super ImportedConfig> action) {
action.execute(imported);
}

public ExportedConfig getExported() {
return exported;
}

public void exported(Action<? super ExportedConfig> action) {
action.execute(exported);
}

public static class ImportedConfig extends BaseConfig{

}

public static class ExportedConfig extends BaseConfig{

}

}
Loading
Loading