From 723d799a642ae4887dbf36e275a4fc47df4143fa Mon Sep 17 00:00:00 2001 From: Lennon Scariano Date: Mon, 13 Apr 2026 14:57:56 -0400 Subject: [PATCH 1/2] init osgi task in plugin --- .gitignore | 48 ++++ build.gradle | 34 +++ gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 234 ++++++++++++++++++ gradlew.bat | 89 +++++++ settings.gradle | 1 + .../groovy/org/sensorhub/OshPlugin.groovy | 211 ++++++++++++++++ 7 files changed, 623 insertions(+) create mode 100644 .gitignore create mode 100644 build.gradle create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/groovy/org/sensorhub/OshPlugin.groovy diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e02f483 --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +.gradle +**/build/ +!**/src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +.idea \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d299317 --- /dev/null +++ b/build.gradle @@ -0,0 +1,34 @@ +plugins { + id 'com.gradle.plugin-publish' version '2.0.0' + id 'java-gradle-plugin' + id 'groovy' +} + +group = 'org.sensorhub' +version = '1.0' + +repositories { + mavenCentral() + maven { + url "https://plugins.gradle.org/m2/" + } +} + +dependencies { + implementation localGroovy() + implementation 'biz.aQute.bnd:biz.aQute.bnd.gradle:6.1.0' +} + +gradlePlugin { + website = 'https://opensensorhub.org/' + vcsUrl = 'https://github.com/opensensorhub/osh-gradle-plugins' + plugins { + register('osh-plugin') { + id = 'org.sensorhub.osh-plugin' + displayName = 'OSH Gradle Plugin' + description = 'Gradle tasks for building, publishing and releasing gradle based osh drivers' + tags.addAll('osh', 'opensensorhub') + implementationClass = 'org.sensorhub.OshPlugin' + } + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d90e3fe --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Apr 07 13:53:52 EDT 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# 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. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..0c1f965 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'osh-gradle-plugins' \ No newline at end of file diff --git a/src/main/groovy/org/sensorhub/OshPlugin.groovy b/src/main/groovy/org/sensorhub/OshPlugin.groovy new file mode 100644 index 0000000..c6b3ed8 --- /dev/null +++ b/src/main/groovy/org/sensorhub/OshPlugin.groovy @@ -0,0 +1,211 @@ +package org.sensorhub + +import org.gradle.api.GradleException +import org.gradle.api.Plugin +import org.gradle.api.Project + +import java.nio.file.FileSystems +import java.nio.file.Files + +class OshPlugin implements Plugin { + void apply(Project project) { + + project.pluginManager.apply('java') + + // OSGi bundle jar task + project.tasks.register("osgi", aQute.bnd.gradle.Bundle) { + from project.sourceSets.main.output + archiveClassifier = 'bundle' + bundle { + classpath = project.sourceSets.main.compileClasspath + } + + // copy embedded libs into bundle jar + into('lib') { + from { + project.configurations.embedded + } + } + + // helper method to list all non-empty packages in class folder + def getPackagesFromDir = { rootDir, packageSet -> + rootDir.eachDirRecurse { dir -> + //println dir + // skip some directories + if (dir.toString().startsWith(File.separator + 'META-INF')) { + return; + } + + // keep only packages that have java class files in them + Files.list(dir) + .filter { it.toString().endsWith('.class') } + .findAny() + .ifPresent { + // Using File.separator in the replace calls on windows does not seem to work and messes up the creation + // of the manifest files + if (rootDir.relativize(dir).toString().contains('\\')) { + packageSet.add(rootDir.relativize(dir).toString() + .replace('\\', '.') + '.*') + } else { + packageSet.add(rootDir.relativize(dir).toString() + .replace('/', '.') + '.*') + } + } + } + } + + // helper method to list all non-empty packages in jar + def getPackagesFromJar = { jarFile, packageSet -> + //println jarFile + FileSystems.newFileSystem(jarFile.toPath(), ClassLoader.getSystemClassLoader()).withCloseable { fs -> + def rootDir = fs.getPath('/') + getPackagesFromDir(rootDir, packageSet) + } + } + + + + // help method to automatically find osgi activator class + def findActivator = { + for (def classDir : project.sourceSets.main.output.classesDirs) { + def rootDir = classDir.toPath() + def activatorClass = Files.walk(rootDir) + .filter { it.toString().endsWith('Activator.class') } + .map { + rootDir.relativize(it).toString() + .replace(java.io.File.separatorChar, (char) '.') + .replaceAll('.class$', '') + } + .findAny() + .orElse(null) + if (activatorClass) + return activatorClass + } + } + + doFirst { + // configure bnd options before running the task + manifest { + //if (!attributes['Import-Package']) + // attributes 'Import-Package': '!java.*,!com.sun.*,!sun.*,!javax.xml.*,!org.xml.sax.*,!org.w3c.dom.*,*' + //attributes '-noimportjava': true + //attributes '-sources': true + + // ignore some common errors + attributes '-fixupmessages': 'Classes found in the wrong directory; is:=ignore,' + + 'Unused Import-Package instructions; is:=ignore,' + + 'The default package \'.\' is not permitted by the Import-Package syntax; is:=ignore,' + + 'Unused Export-Package instructions; is:=ignore,' + + // disable DS annotation processing + if (!attributes['-dsannotations']) + attributes '-dsannotations': '!*' + + // auto detect bundle activator if not configured + if (!attributes['Bundle-Activator']) { + def activatorClass = findActivator() + //println activatorClass + if (activatorClass) + attributes 'Bundle-Activator': activatorClass + } + + // compute imports/exports based on gradle dependencies + def embeddedJars = project.configurations.embedded + def depJars = project.configurations.compileClasspath.minus(embeddedJars) + def apiJars = project.configurations.embeddedApi + + // import all packages from all dependencies that are not embedded + def importedPackages = [] as Set + depJars.each { + getPackagesFromJar(it, importedPackages) + } + //println importedPackages + if (!attributes['Import-Package']) + attributes 'Import-Package': importedPackages.join(',') + + // export packages in API dependencies and in this project + def exportedPackages = [] as Set + project.sourceSets.main.output.classesDirs.each { + getPackagesFromDir(it.toPath(), exportedPackages) + } + apiJars.each { + getPackagesFromJar(it, exportedPackages) + } + //println exportedPackages + if (!attributes['-exportcontents']) + attributes '-exportcontents': exportedPackages.join(',') + + /*// add all dependencies that are not embedded to Require-Bundle + attributes 'Import-Package': '!*' + def embeddedDeps = project.configurations.embedded.allDependencies + def apiDeps = project.configurations.api.allDependencies.minus(embeddedDeps) + def implDeps = project.configurations.implementation.allDependencies.minus(apiDeps).minus(embeddedDeps) + def requiredBundles = '' + apiDeps.each { + if (!requiredBundles.isEmpty()) requiredBundles += ',' + requiredBundles += it.group + '.' + it.name + ';bundle-version:="' + it.version + '";visibility:=reexport' + } + implDeps.each { + if (!requiredBundles.isEmpty()) requiredBundles += ',' + requiredBundles += it.group + '.' + it.name + ';bundle-version:="' + it.version + '"' + } + attributes 'Require-Bundle': requiredBundles*/ + + /*// add embedded jars to OSGi classpath + // only add jars that were not substituted with newer version by gradle + def classpath = '.' + def embeddedJars = '' + def runtimeDeps = project.configurations.runtimeClasspath.collect { it.name }; + project.configurations.embedded.each { + if (runtimeDeps.contains(it.name)) { + embeddedJars += 'lib/' + it.name + '=' + it.name + ';lib:=true,' + } + } + attributes '-includeresource': embeddedJars*/ + + // add embedded jars to OSGi classpath + // we do it like this so imports are not computed for these + def classpath = '.' + def embeddedClasspath = '' + def runtimeDeps = project.configurations.runtimeClasspath.collect { it.name } + project.configurations.embedded.each { + if (runtimeDeps.contains(it.name)) { + embeddedClasspath += 'lib/' + it.name + ',' + } + } + attributes 'Bundle-ClassPath': embeddedClasspath + '.' + + // auto-generate Bundle-NativeCode header if native libs are placed in + // the lib/native resource folder with the proper directory structure + def resourcesFolder = new File(project.projectDir, '/src/main/resources') + def nativeFolder = new File(resourcesFolder, '/lib/native') + if (nativeFolder.exists()) { + def currentPlatform = '' + def nativePaths = '' + fileTree(dir: nativeFolder).files.each { + def path = resourcesFolder.toPath().relativize(it.toPath()) + if (path.nameCount != 5) { + throw new GradleException("Invalid native library path in resource folder: " + path + + ". Path must be of the form 'lib/native/{osname}/{arch}/{libname}.{ext}'") + } + + // lib paths must be grouped by platform (os and processor) + def osname = path.getName(2) + def proc = path.getName(3) + def platform = 'osname=' + osname + '; processor=' + proc + if (platform != currentPlatform) { + nativePaths = platform + (nativePaths.isEmpty() ? '' : ', ' + nativePaths) + currentPlatform = platform; + } + + nativePaths = path.toString().replace('\\', '/') + '; ' + nativePaths + } + + attributes 'Bundle-NativeCode': nativePaths + } + } + } + } + + } +} \ No newline at end of file From a02aeb334a736d47da945ae0a0a5f8ac0c89b488 Mon Sep 17 00:00:00 2001 From: Lennon Scariano Date: Mon, 13 Apr 2026 16:01:34 -0400 Subject: [PATCH 2/2] add readme, pull in common files --- README.md | 27 +++++ common/common.gradle | 239 ++++++++++++++++++++++++++++++++++++++++++ common/release.gradle | 159 ++++++++++++++++++++++++++++ 3 files changed, 425 insertions(+) create mode 100644 README.md create mode 100644 common/common.gradle create mode 100644 common/release.gradle diff --git a/README.md b/README.md new file mode 100644 index 0000000..e7b0a4e --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# OSH Gradle Plugins + +Project containing common build files for osh projects, as well as a plugin containing common build tasks + +## Usage instructions + +### Common Build Files + +Include this repository as a git submodule, and use +``` +apply from: 'path_to_submodules/osh-gradle-plugins/common/common.gradle' +apply from: 'path_to_submodules/osh-gradle-plugins/common/release.gradle' +``` + +### Plugin + +If pulling in as a submodule, then use `includeBuild path_to_submodules/osh-gradle-plugins` in your `settings.gradle` and declare plugin normally: + +``` +plugins { + id 'org.sensorhub.osh-plugin' +} +``` +or +`apply plugin: 'org.sensorhub.osh-plugin'` + +If not pulling in as a submodule, and this plugin is hosted on the gradle plugin repository, then a simple plugin declaration will suffice. diff --git a/common/common.gradle b/common/common.gradle new file mode 100644 index 0000000..ea343b9 --- /dev/null +++ b/common/common.gradle @@ -0,0 +1,239 @@ +import java.nio.file.*; + +ext.oshCoreVersion = '2.0.0' + + +buildscript { + repositories { + maven { + url "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath "biz.aQute.bnd:biz.aQute.bnd.gradle:6.1.0" + } +} + + +allprojects { + group = 'org.sensorhub' + + repositories { + mavenCentral() + } + + // set build number to HEAD SHA-1 + def stdout = new ByteArrayOutputStream() + exec { + commandLine('git', 'rev-parse', '--short', 'HEAD') + standardOutput = stdout + // hide errors and don't throw exception if not a git repo + errorOutput = new ByteArrayOutputStream() + ignoreExitValue = true + } + ext.buildNumber = "$stdout".trim() + + afterEvaluate { project -> + if (project.hasProperty('sourceCompatibility')) { + project.sourceCompatibility = 17 + project.targetCompatibility = 17 + } + } +} + + +subprojects { + apply plugin: 'java-library' + apply plugin: 'java-test-fixtures' + apply plugin: 'eclipse' + apply plugin: 'maven-publish' + apply plugin: 'org.sensorhub.osh-plugin' + + ext.details = null + ext.pom = {} // pom data that subprojects can append to + + tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' + options.compilerArgs << "-Xlint:-options" + } + + tasks.withType(Javadoc) { + options.encoding = 'UTF-8' + options.addStringOption('Xdoclint:none', '-quiet') + } + + eclipse { + classpath { + downloadJavadoc = true + file.whenMerged { + entries.each { + if (it.hasProperty('exported')) + it.exported = true + } + } + } + } + + // custom dependency configurations for embedding jars in OSGi bundle + configurations { + embeddedApi + embeddedImpl + embedded + embedded.extendsFrom(embeddedApi, embeddedImpl) + api.extendsFrom(embeddedApi) + implementation.extendsFrom(embeddedImpl) + } + + // default test dependencies + dependencies { + testImplementation 'junit:junit:4.13' + testImplementation 'xmlunit:xmlunit:1.6' + } + + // print test names + test { + testLogging { + events 'PASSED', 'FAILED' + showCauses true + showStackTraces true + exceptionFormat 'full' + } + } + + assemble.dependsOn osgi + + // do stuff at the end in case subprojects add extra info + afterEvaluate { project -> + + // set defaults for some OSGi manifest entries + project.osgi { + manifest { + // main info + attributes 'Bundle-SymbolicName': project.group + '.' + project.name + if (project.description != null && !attributes['Bundle-Name']) + attributes 'Bundle-Name': project.description + if (project.details != null && !attributes['Bundle-Description']) + attributes 'Bundle-Description': project.details + attributes 'Bundle-Version': project.version + if (project.buildNumber != null && !project.buildNumber.isEmpty()) + attributes 'Bundle-BuildNumber': project.buildNumber + if (!attributes['Bundle-License']) + attributes 'Bundle-License': 'MPL 2.0 (http://mozilla.org/MPL/2.0)' + if (!attributes['Bundle-Copyright'] && attributes['Bundle-Vendor']) + attributes 'Bundle-Copyright': 'Copyright (c) ' + attributes['Bundle-Vendor'] + '. All Rights Reserved' + } + } + + // also use osgi headers in JAR manifest + project.jar { + manifest { + from project.osgi.manifest + } + } + + // maven artifact content + project.publishing { + + publications { + mavenJava(MavenPublication) { + from components.java + pom.withXml { + asNode().get('version') + ({ + resolveStrategy = Closure.DELEGATE_FIRST + name project.description + if (project.details != null) + description project.details + url 'http://www.opensensorhub.org' + licenses { + license { + name 'Mozilla Public License Version 2.0' + url 'http://www.mozilla.org/MPL/2.0' + distribution 'repo' + } + } + def repoName = projectDir.parentFile.name + scm { + url 'https://github.com/opensensorhub/' + repoName + '/tree/master/' + project.name + connection 'scm:git:git://github.com/opensensorhub/' + repoName + '.git' + } + issueManagement { + url 'https://github.com/opensensorhub/' + repoName + '/issues' + system 'GitHub Issues' + } + } >> project.pom) + } + } + } + repositories { + maven { + name = "GitHubPackages" + url = "https://maven.pkg.github.com/opensensorhub/osh-core" + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } + } + } + + project.tasks.named("generateMetadataFileForMavenJavaPublication") { + doFirst { + if (System.getenv("GITHUB_ACTOR") == null) { + throw new Exception("Environment variable GITHUB_ACTOR not set. Please set to your github username.") + } + + if (System.getenv("GITHUB_TOKEN") == null) { + throw new Exception("Environment variable GITHUB_TOKEN not set. Please generate and set to your personal access token: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens") + } + } + } + + project.tasks.named("publishMavenJavaPublicationToGitHubPackagesRepository") { + onlyIf { + // + MavenArtifactRepository repo = repository as MavenArtifactRepository; + MavenPublication pub = publication as MavenPublication; + + HttpURLConnection connection = new URL("$repo.url/${pub.groupId.replace('.', '/')}/$pub.artifactId/$pub.version/$pub.artifactId-${pub.version}.jar").openConnection(); + connection.setRequestMethod("GET"); + connection.setRequestProperty("Authorization", "Basic ${new String(Base64.getEncoder().encode("$repo.credentials.username:$repo.credentials.password".bytes))}"); + connection.connect(); + return connection.responseCode == 404; + } + } + } + + // disable jar task if no source is included + if (!new File(project.projectDir, 'src').exists()) { + tasks.osgi.enabled = false + tasks.jar.enabled = false + } + + // custom task to install in local maven repo + task install + install.dependsOn(build) + install.dependsOn(publishToMavenLocal) +} + + +// distribution zip files +apply plugin: 'java-library' +apply plugin: 'distribution' + +tasks.jar.enabled = false +afterEvaluate { // disable all distTar tasks + tasks.each { + if (it.name.endsWith('istTar')) + it.enabled = false + } +} + + +// collect all configured repositories in parent build +gradle.projectsEvaluated { g -> + if (gradle.parent != null) { + gradle.parent.rootProject { + repositories.addAll(g.rootProject.repositories) + } + } +} diff --git a/common/release.gradle b/common/release.gradle new file mode 100644 index 0000000..26826e8 --- /dev/null +++ b/common/release.gradle @@ -0,0 +1,159 @@ + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'org.ajoberstar:gradle-git:1.6.0' + classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.2.1' + classpath 'org.kohsuke:github-api:1.132' + } +} + + +//apply plugin: org.sonarqube.gradle.SonarQubePlugin +apply plugin: org.ajoberstar.gradle.git.base.GrgitPlugin + + +/* Bintray was shutdown in Feb 2021 */ +/*subprojects { + afterEvaluate { project -> + // only publish with bintray if credentials are configured + // and project is not a SNAPSHOT + if (project.hasProperty("bintray_user") && !project.version.endsWith('SNAPSHOT')) { + // bintray publishing options + bintray { + user = bintray_user + key = bintray_api_key + + publications = ['mavenJava'] + dryRun = false // whether to run this as dry-run, without deploying + publish = true // whether version should be auto published after an upload + override = true // whether to override version artifacts already published + + pkg { + repo = 'osh' + name = rootProject.name + userOrg = 'sensiasoft' + if (rootProject.description != null) + desc = rootProject.description + websiteUrl = 'https://github.com/opensensorhub/' + rootProject.name + issueTrackerUrl = 'https://github.com/opensensorhub/' + rootProject.name + '/issues' + vcsUrl = 'git://github.com/opensensorhub/' + rootProject.name + '.git' + licenses = ['MPL-2.0'] + labels = ['sensor', 'sensor hub', 'ogc', 'swe', 'iot'] + publicDownloadNumbers = true + version { + name = rootProject.version + } + } + } + } + } +}*/ + + +// this task checks that release conditions are met +task prerelease { + doLast { + println 'Current version is ' + version + println 'Current HEAD is ' + grgit.head().abbreviatedId + + // check that we're on master branch + if (grgit.branch.current.name != 'master') + throw new GradleException('A release can only be done from the master branch. First merge your changes to master') + + // check that current version is not a snapshot + if (version.endsWith('SNAPSHOT')) + throw new GradleException('Cannot release a SNAPSHOT. Please update the project version number') + + // check that we don't have any snapshot dependencies + + // check that there is no existing tag with this version + // this ensures version has been incremented since last release + def tags = grgit.tag.list() + tags.each { + if (it.name == 'v' + version) + throw new GradleException('Version ' + version + ' has already been released (existing tag)') + } + + // check for uncommited files + def status = grgit.status() + if (!status.isClean()) { + throw new GradleException('Local version has uncommited changes') + } + } +} + + +// this task creates a Git tag +task releaseGit { + doLast { + // tag release version (after successful build) + println '> Adding release tag for version ' + version + grgit.tag.add { + name = 'v' + version + message = 'Release of version ' + version + } + + // push new tag + println '> Pushing new tag to remote' + grgit.push(tags: true) + } +} + + +// this task creates a GitHub release +import org.kohsuke.github.* +task releaseGithub { + doLast { + println '> Publishing Release to GitHub' + + GitHub gh = GitHub.connect(github_user, github_token); + GHRepository repo = gh.getRepository("opensensorhub/" + project.name); + + // load release template + String text = "" + File templateFile = new File(rootDir, 'release-text.md') + if (templateFile.exists()) { + text = templateFile.text; + } + + // find version milestone + def milestone = repo.listMilestones(GHIssueState.ALL).find { + it.title == 'v' + project.version + } + if (milestone == null) { + println 'No milestone found for release version ' + project.version + } + else { + // append issues fixed for this milestone + def issues = repo.getIssues(GHIssueState.CLOSED, milestone) + if (!issues.isEmpty()) + text += "Resolved Issues:\n\n" + issues.each { + text += " * **#" + it.number + "** " + it.title + "\n" + } + println text + } + + // publish new release + GHReleaseBuilder builder = repo.createRelease('v' + project.version); + builder.name(project.name + " v" + project.version) + .draft(true) + .body(text) + .create() + } +} + + +// release subtasks ordering +// prerelease > build > releaseGit > bintrayUpload > releaseGithub +task release +build.shouldRunAfter prerelease +releaseGit.dependsOn prerelease +releaseGit.dependsOn build +/*bintrayUpload.dependsOn releaseGit*/ +releaseGithub.dependsOn releaseGit +release.dependsOn releaseGithub +