Skip to content
Snippets Groups Projects
Commit 13b51be3 authored by Sebastian's avatar Sebastian
Browse files

Convert buildSrc to kotlin

parent 820f3d4d
No related branches found
No related tags found
1 merge request!90Add plugin in buildSrc to provide some build metadata to app at runtime
Showing
with 243 additions and 289 deletions
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("java")
kotlin("jvm") version "1.6.10"
id("org.jlleitschuh.gradle.ktlint") version "10.1.0"
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}
repositories {
......
package org.briarproject.briar.desktop.builddata;
import org.gradle.api.internal.ConventionTask;
import org.gradle.api.logging.Logger;
import org.gradle.api.tasks.Nested;
public abstract class AbstractBuildDataTask extends ConventionTask {
protected final Logger logger = getLogger();
@Nested
protected BuildDataPluginExtension configuration;
public BuildDataPluginExtension getConfiguration() {
return configuration;
}
public void setConfiguration(BuildDataPluginExtension configuration) {
this.configuration = configuration;
}
}
package org.briarproject.briar.desktop.builddata;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSet;
import java.nio.file.Path;
public class BuildDataPlugin implements Plugin<Project> {
@Override
public void apply(final Project project) {
Logger logger = project.getLogger();
logger.info("applying version access plugin");
BuildDataPluginExtension extension = project.getExtensions().create(
"buildData", BuildDataPluginExtension.class);
GenerateBuildDataSourceTask task = project.getTasks().create(
"buildData", GenerateBuildDataSourceTask.class);
task.setConfiguration(extension);
project.getTasks().findByName("compileJava").dependsOn(task);
Path pathBuildDir = project.getBuildDir().toPath();
Path source = Util.getSourceDir(pathBuildDir);
SourceSet sourceSets = project.getConvention()
.getPlugin(JavaPluginConvention.class).getSourceSets()
.findByName("main");
sourceSets.java(sourceSet -> {
sourceSet.srcDir(source);
});
}
}
package org.briarproject.briar.desktop.builddata;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
public class BuildDataPluginExtension {
@Input
private String packageName;
@Input
@Optional
private String className;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
package org.briarproject.briar.desktop.builddata;
class FileBuilder {
private static String nl = System.getProperty("line.separator");
private StringBuilder buffer = new StringBuilder();
void append(String string) {
buffer.append(string);
}
void line() {
buffer.append(nl);
}
void line(String string) {
buffer.append(string);
buffer.append(nl);
}
public String toString() {
return buffer.toString();
}
}
package org.briarproject.briar.desktop.builddata;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.gradle.api.GradleScriptException;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class GenerateBuildDataSourceTask extends AbstractBuildDataTask {
public GenerateBuildDataSourceTask() {
setGroup("build");
}
@TaskAction
protected void generateSource() throws IOException {
Project project = getProject();
String packageName = configuration.getPackageName();
String className = configuration.getClassName();
if (className == null) {
className = "BuildData";
}
/*
* Get version from Gradle project information
*/
String version = project.getVersion().toString();
/*
* Get Git hash, last commit time and current branch using JGit
*/
// Open git repository
File dir = project.getProjectDir();
Git git = Git.open(dir);
Repository repository = git.getRepository();
// Get head ref and it's name => current hash
ObjectId head = repository.resolve(Constants.HEAD);
String gitHash = head.getName();
// Get latest commit and its commit time
RevCommit first;
try {
first = getLastCommit(git);
} catch (GitAPIException | NoSuchElementException e) {
throw new GradleScriptException("Error while fetching commits", e);
}
// Convert from seconds to milliseconds
long commitTime = first.getCommitTime() * 1000L;
// Get current branch, if any
String gitBranch = "<unknown>";
String prefix = "refs/heads/";
String fullBranch = repository.getFullBranch();
if (fullBranch.startsWith(prefix)) {
gitBranch = fullBranch.substring(prefix.length());
}
/*
* Generate output file
*/
if (packageName == null) {
throw new IllegalStateException(
"Please specify 'packageName'.");
}
String[] parts = packageName.split("\\.");
Path pathBuildDir = project.getBuildDir().toPath();
Path source = Util.getSourceDir(pathBuildDir);
Path path = source;
for (int i = 0; i < parts.length; i++) {
path = path.resolve(parts[i]);
}
Files.createDirectories(path);
Path file = path.resolve(className + ".java");
String content = createSource(packageName, className, version,
commitTime, gitHash, gitBranch);
InputStream in = new ByteArrayInputStream(
content.getBytes(StandardCharsets.UTF_8));
Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
}
private RevCommit getLastCommit(Git git) throws GitAPIException {
Iterable<RevCommit> commits = git.log().call();
Iterator<RevCommit> iterator = commits.iterator();
if (!iterator.hasNext()) {
throw new NoSuchElementException();
}
return iterator.next();
}
private String createSource(String packageName, String className,
String version, long gitTime, String gitHash, String gitBranch) {
FileBuilder buffer = new FileBuilder();
// // this file is generated, do not edit
// package org.briarproject.briar.desktop;
//
// public class BuildData {
buffer.line("// this file is generated, do not edit");
buffer.line("package " + packageName + ";");
buffer.line();
buffer.line("public class " + className + " {");
buffer.line();
// public static String getVersion() {
// return "0.1";
// }
buffer.line(" public static String getVersion() {");
buffer.line(" return \"" + version + "\";");
buffer.line(" }");
buffer.line();
// public static long getGitTime() {
// return 1641645802088L;
// }
buffer.line(" public static long getGitTime() {");
buffer.line(" return " + gitTime + "L;");
buffer.line(" }");
buffer.line();
// public static long getGitHash() {
// return "749dda081c3e7862050255817bc239b9255b1582";
// }
buffer.line(" public static String getGitHash() {");
buffer.line(" return \"" + gitHash + "\";");
buffer.line(" }");
buffer.line();
// public static String getGitBranch() {
// return "master";
// }
buffer.line(" public static String getGitBranch() {");
buffer.line(" return \"" + gitBranch + "\";");
buffer.line(" }");
buffer.line();
buffer.line("}");
return buffer.toString();
}
}
package org.briarproject.briar.desktop.builddata;
import java.nio.file.Path;
class Util {
static Path getSourceDir(Path pathBuildDir) {
return pathBuildDir.resolve("generatedBuildData");
}
}
package org.briarproject.briar.desktop.builddata
import org.gradle.api.internal.ConventionTask
import org.gradle.api.tasks.Nested
abstract class AbstractBuildDataTask : ConventionTask() {
@Nested
var configuration: BuildDataPluginExtension? = null
}
package org.briarproject.briar.desktop.builddata
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.plugins.JavaPluginConvention
class BuildDataPlugin : Plugin<Project> {
override fun apply(project: Project) {
val logger = project.logger
logger.info("applying version access plugin")
val extension = project.extensions.create(
"buildData", BuildDataPluginExtension::class.java
)
val task = project.tasks.create(
"buildData", GenerateBuildDataSourceTask::class.java
)
task.configuration = extension
project.tasks.findByName("compileJava")!!.dependsOn(task)
val pathBuildDir = project.buildDir.toPath()
val source = Util.getSourceDir(pathBuildDir)
val sourceSets = project.convention
.getPlugin(JavaPluginConvention::class.java).sourceSets
.findByName("main")
sourceSets!!.java { sourceSet: SourceDirectorySet -> sourceSet.srcDir(source) }
}
}
package org.briarproject.briar.desktop.builddata
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
open class BuildDataPluginExtension {
@Input
var packageName: String? = null
@Input
@Optional
var className: String? = null
}
package org.briarproject.briar.desktop.builddata
internal class FileBuilder {
private val buffer = StringBuilder()
fun line() {
buffer.append(nl)
}
fun line(string: String?) {
buffer.append(string)
buffer.append(nl)
}
override fun toString(): String {
return buffer.toString()
}
companion object {
private val nl = System.getProperty("line.separator")
}
}
package org.briarproject.briar.desktop.builddata
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.errors.GitAPIException
import org.eclipse.jgit.lib.Constants
import org.eclipse.jgit.revwalk.RevCommit
import org.gradle.api.GradleScriptException
import org.gradle.api.tasks.TaskAction
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.StandardCopyOption
open class GenerateBuildDataSourceTask : AbstractBuildDataTask() {
init {
group = "build"
}
@TaskAction
@Throws(IOException::class)
protected fun generateSource() {
val project = project
val packageName = configuration?.packageName
var className = configuration?.className
if (className == null) {
className = "BuildData"
}
/*
* Get version from Gradle project information
*/
val version = project.version.toString()
/*
* Get Git hash, last commit time and current branch using JGit
*/
// Open git repository
val dir = project.projectDir
val git = Git.open(dir)
val repository = git.repository
// Get head ref and it's name => current hash
val head = repository.resolve(Constants.HEAD)
val gitHash = head.name
// Get latest commit and its commit time
val first: RevCommit = try {
getLastCommit(git)
} catch (e: GitAPIException) {
throw GradleScriptException("Error while fetching commits", e)
} catch (e: NoSuchElementException) {
throw GradleScriptException("Error while fetching commits", e)
}
// Convert from seconds to milliseconds
val commitTime = first.commitTime * 1000L
// Get current branch, if any
var gitBranch = "<unknown>"
val prefix = "refs/heads/"
val fullBranch = repository.fullBranch
if (fullBranch.startsWith(prefix)) {
gitBranch = fullBranch.substring(prefix.length)
}
/*
* Generate output file
*/
checkNotNull(packageName) { "Please specify 'packageName'." }
val parts = packageName.split("\\.".toRegex()).toTypedArray()
val pathBuildDir = project.buildDir.toPath()
val source = Util.getSourceDir(pathBuildDir)
var path = source
for (i in parts.indices) {
path = path.resolve(parts[i])
}
Files.createDirectories(path)
val file = path.resolve("$className.java")
val content = createSource(
packageName, className, version,
commitTime, gitHash, gitBranch
)
val `in`: InputStream = ByteArrayInputStream(
content.toByteArray(StandardCharsets.UTF_8)
)
Files.copy(`in`, file, StandardCopyOption.REPLACE_EXISTING)
}
@Throws(GitAPIException::class)
private fun getLastCommit(git: Git): RevCommit {
val commits = git.log().call()
val iterator: Iterator<RevCommit> = commits.iterator()
if (!iterator.hasNext()) {
throw NoSuchElementException()
}
return iterator.next()
}
private fun createSource(
packageName: String,
className: String,
version: String,
gitTime: Long,
gitHash: String,
gitBranch: String,
): String {
return FileBuilder().also {
with(it) {
line("// this file is generated, do not edit")
// // this file is generated, do not edit
// package org.briarproject.briar.desktop;
//
// public class BuildData {
line("// this file is generated, do not edit")
line("package $packageName;")
line()
line("public class $className {")
line()
// public static String getVersion() {
// return "0.1";
// }
line(" public static String getVersion() {")
line(" return \"$version\";")
line(" }")
line()
// public static long getGitTime() {
// return 1641645802088L;
// }
line(" public static long getGitTime() {")
line(" return " + gitTime + "L;")
line(" }")
line()
// public static long getGitHash() {
// return "749dda081c3e7862050255817bc239b9255b1582";
// }
line(" public static String getGitHash() {")
line(" return \"$gitHash\";")
line(" }")
line()
// public static String getGitBranch() {
// return "master";
// }
line(" public static String getGitBranch() {")
line(" return \"$gitBranch\";")
line(" }")
line()
line("}")
}
}.toString()
}
}
package org.briarproject.briar.desktop.builddata
import java.nio.file.Path
internal object Util {
fun getSourceDir(pathBuildDir: Path): Path {
return pathBuildDir.resolve("generatedBuildData")
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment