chore: merge branch 'java-ci' into dev

This commit is contained in:
əlemi 2024-09-18 16:04:51 +02:00
commit 2cdc77eaec
Signed by: alemi
GPG key ID: A4895B84D311642C
9 changed files with 234 additions and 104 deletions

View file

@ -30,6 +30,10 @@ jobs:
- uses: arduino/setup-protoc@v3 - uses: arduino/setup-protoc@v3
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '11'
- uses: gradle/actions/setup-gradle@v4 - uses: gradle/actions/setup-gradle@v4
with: with:
gradle-version: "8.10" # Quotes required to prevent YAML converting to number gradle-version: "8.10" # Quotes required to prevent YAML converting to number
@ -39,5 +43,10 @@ jobs:
with: with:
name: codemp-java-${{ matrix.platform.target }} name: codemp-java-${{ matrix.platform.target }}
path: dist/java/build/libs path: dist/java/build/libs
- run: gradle publish
# TODO add a publish step to maven central working-directory: dist/java
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.MAVEN_CENTRAL_GPG_SECRET_KEY }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.MAVEN_CENTRAL_GPG_PASSWORD }}

View file

@ -2,11 +2,11 @@
[![Actions Status](https://github.com/hexedtech/codemp/actions/workflows/test.yml/badge.svg)](https://github.com/hexedtech/codemp/actions) [![Actions Status](https://github.com/hexedtech/codemp/actions/workflows/test.yml/badge.svg)](https://github.com/hexedtech/codemp/actions)
[![docs.rs Status](https://img.shields.io/docsrs/codemp)](https://docs.rs/codemp/) [![docs.rs Status](https://img.shields.io/docsrs/codemp)](https://docs.rs/codemp/)
[![Gitter Chat](https://img.shields.io/gitter/room/hexedtech/codemp)](https://gitter.im/hexedtech/codemp)
[![Crates.io Version](https://img.shields.io/crates/v/codemp)](https://crates.io/crates/codemp) [![Crates.io Version](https://img.shields.io/crates/v/codemp)](https://crates.io/crates/codemp)
[![NPM Version](https://img.shields.io/npm/v/codemp)](https://npmjs.org/package/codemp) [![Gitter Chat](https://img.shields.io/gitter/room/hexedtech/codemp)](https://gitter.im/hexedtech/codemp)
[![PyPI Version](https://img.shields.io/pypi/v/codemp)](https://pypi.org/project/codemp) [![GitHub last commit](https://img.shields.io/github/last-commit/hexedtech/codemp)](https://github.com/hexedtech/codemp/commits/dev/)
[![LuaRocks Version](https://img.shields.io/luarocks/v/alemi/codemp)](https://luarocks.org/modules/alemi/codemp) [![GitHub commits since tagged version](https://img.shields.io/github/commits-since/hexedtech/codemp/v0.6.2)](https://github.com/hexedtech/codemp/releases/tag/v0.6.2)
[![Crates.io License](https://img.shields.io/crates/l/codemp)](https://github.com/hexedtech/codemp/blob/dev/LICENSE)
> `codemp` is a **collaborative** text editing solution to work remotely. > `codemp` is a **collaborative** text editing solution to work remotely.
@ -55,11 +55,17 @@ Adding a dependency on `codemp` is **easy**:
Just `cargo add codemp` and check the docs for some examples. Just `cargo add codemp` and check the docs for some examples.
### From supported languages ### From supported languages
We provide first-class bindings for: We provide first-class bindings for these other programming languages:
- [![JavaScript](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml/badge.svg)](./dist/README.md#javascript) available from `npm` as [`codemp`](https://npmjs.org/package/codemp)
- [![Python](https://github.com/hexedtech/codemp/actions/workflows/python.yml/badge.svg)](./dist/README.md#python) available from `PyPI` as [`codemp`](https://pypi.org/project/codemp)
- [![Lua](https://github.com/hexedtech/codemp/actions/workflows/lua.yml/badge.svg)](./dist/README.md#lua) available from `LuaRocks` as [`codemp`](https://luarocks.org/modules/alemi/codemp) | | Build Status | Package | Build Instructions |
- [![Java](https://github.com/hexedtech/codemp/actions/workflows/java.yml/badge.svg)](./dist/README.md#java) available on `MavenCentral` **SOON** | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| JavaScript | [![JavaScript Build](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml) | [![NPM Version](https://img.shields.io/npm/v/codemp)](https://npmjs.org/package/codemp) | [README](./dist/README.md#javascript) |
| Python | [![Python Build](https://github.com/hexedtech/codemp/actions/workflows/python.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/python.yml) | [![PyPI Version](https://img.shields.io/pypi/v/codemp)](https://pypi.org/project/codemp) | [README](./dist/README.md#python) |
| Java | [![Java Build](https://github.com/hexedtech/codemp/actions/workflows/java.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/java.yml) | [![LuaRocks Version](https://img.shields.io/luarocks/v/alemi/codemp)](https://luarocks.org/modules/alemi/codemp) | [README](./dist/README.md#java) |
| Lua | [![Lua Build](https://github.com/hexedtech/codemp/actions/workflows/lua.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/lua.yml) | [![Maven Central Version](https://img.shields.io/maven-central/v/mp.code/codemp)](https://central.sonatype.com/artifact/mp.code/codemp) | [README](./dist/README.md#lua) |
As a design philosophy, our binding APIs attempt to perfectly mimic their Rust counterparts, so the main documentation can still be referenced as source of truth. As a design philosophy, our binding APIs attempt to perfectly mimic their Rust counterparts, so the main documentation can still be referenced as source of truth.
Refer to specific language documentation for specifics, differences and quirks. Refer to specific language documentation for specifics, differences and quirks.

View file

@ -1,20 +1,18 @@
plugins { plugins {
id 'java-library' id 'java-library'
id 'maven-publish' id "com.vanniktech.maven.publish" version "0.29.0"
id 'com.github.johnrengelman.shadow' version '8.1.1' id 'com.google.osdetector' version '1.7.3'
id 'com.palantir.git-version' version '3.1.0'
} }
group = 'mp.code' group = 'mp.code'
version = versionDetails().lastTag.substring(1) version = '0.0.3'
java { java {
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = targetCompatibility = JavaVersion.VERSION_11
} }
repositories { repositories {
mavenCentral() mavenCentral()
maven { url 'https://jitpack.io' }
} }
sourceSets { sourceSets {
@ -22,18 +20,17 @@ sourceSets {
} }
dependencies { dependencies {
implementation 'com.github.adamheinrich:native-utils:master-SNAPSHOT'
compileOnly 'org.projectlombok:lombok:1.18.34' compileOnly 'org.projectlombok:lombok:1.18.34'
annotationProcessor 'org.projectlombok:lombok:1.18.34' annotationProcessor 'org.projectlombok:lombok:1.18.34'
} }
shadowJar { tasks.register('cargoBuild', Exec) {
archiveClassifier.set('') workingDir '.'
dependencies { commandLine 'cargo', 'build', '--release', '--features=java'
include(dependency('com.github.adamheinrich:native-utils:master-SNAPSHOT'))
}
} }
jar.archiveClassifier = osdetector.classifier
def rustDir = projectDir.toPath() def rustDir = projectDir.toPath()
.parent .parent
.parent .parent
@ -41,6 +38,7 @@ def rustDir = projectDir.toPath()
.resolve('release') .resolve('release')
.toFile() .toFile()
processResources { processResources {
dependsOn cargoBuild
outputs.upToDateWhen { false } // no caching outputs.upToDateWhen { false } // no caching
from(rustDir) { from(rustDir) {
include('*.dll') include('*.dll')
@ -50,54 +48,34 @@ processResources {
} }
} }
tasks.register('cargoBuild', Exec) { import com.vanniktech.maven.publish.SonatypeHost
workingDir '.' mavenPublishing {
commandLine 'cargo', 'build', '--release', '--features=java' publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
} signAllPublications()
coordinates(project.group, rootProject.name, project.version)
processResources.dependsOn cargoBuild pom {
build.finalizedBy shadowJar name = rootProject.name
description = "A collaborative editor plugin ecosystem"
publishing { inceptionYear = "2022"
publications { url = "https://code.mp/"
mavenJava(MavenPublication) { licenses {
artifactId = 'my-library' license {
from components.java name = "The GNU General Public License v3.0"
versionMapping { url = "https://www.gnu.org/licenses/gpl-3.0.txt"
usage('java-api') {
fromResolutionOf('runtimeClasspath')
}
usage('java-runtime') {
fromResolutionResult()
}
} }
pom { }
name = 'My Library' developers {
description = 'A concise description of my library' developer {
url = 'http://www.example.com/library' id = "zaaarf"
properties = [ name = "zaaarf"
myProp: "value", email = "zaaarf@codemp.dev"
"prop.with.dots": "anotherValue"
]
licenses {
license {
name = 'The Apache License, Version 2.0'
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id = 'johnd'
name = 'John Doe'
email = 'john.doe@example.com'
}
}
scm {
connection = 'scm:git:git://example.com/my-library.git'
developerConnection = 'scm:git:ssh://example.com/my-library.git'
url = 'http://example.com/my-library/'
}
} }
} }
scm {
url = "https://github.com/hexedtech/codemp/"
connection = "scm:git:git://github.com/hexedtech/codemp.git"
developerConnection = "scm:git:ssh://git@github.com/hexedtech/codemp.git"
}
} }
} }

View file

@ -17,6 +17,7 @@ public final class BufferController {
BufferController(long ptr) { BufferController(long ptr) {
this.ptr = ptr; this.ptr = ptr;
Extensions.CLEANER.register(this, () -> free(ptr));
} }
private static native String get_name(long self); private static native String get_name(long self);
@ -116,12 +117,8 @@ public final class BufferController {
} }
private static native void free(long self); private static native void free(long self);
@Override
protected void finalize() {
free(this.ptr);
}
static { static {
Extensions.loadLibraryIfNotPresent(); NativeUtils.loadLibraryIfNeeded();
} }
} }

View file

@ -22,6 +22,7 @@ public final class Client {
Client(long ptr) { Client(long ptr) {
this.ptr = ptr; this.ptr = ptr;
Extensions.CLEANER.register(this, () -> free(ptr));
} }
/** /**
@ -146,12 +147,8 @@ public final class Client {
} }
private static native void free(long self); private static native void free(long self);
@Override
protected void finalize() {
free(this.ptr);
}
static { static {
Extensions.loadLibraryIfNotPresent(); NativeUtils.loadLibraryIfNeeded();
} }
} }

View file

@ -16,6 +16,7 @@ public final class CursorController {
CursorController(long ptr) { CursorController(long ptr) {
this.ptr = ptr; this.ptr = ptr;
Extensions.CLEANER.register(this, () -> free(ptr));
} }
private static native Cursor try_recv(long self) throws ControllerException; private static native Cursor try_recv(long self) throws ControllerException;
@ -93,12 +94,8 @@ public final class CursorController {
} }
private static native void free(long self); private static native void free(long self);
@Override
protected void finalize() {
free(this.ptr);
}
static { static {
Extensions.loadLibraryIfNotPresent(); NativeUtils.loadLibraryIfNeeded();
} }
} }

View file

@ -1,6 +1,6 @@
package mp.code; package mp.code;
import java.io.IOException; import java.lang.ref.Cleaner;
/** /**
* A class holding utility functions, as well as functions which are specific * A class holding utility functions, as well as functions which are specific
@ -8,6 +8,9 @@ import java.io.IOException;
* broader CodeMP API. * broader CodeMP API.
*/ */
public final class Extensions { public final class Extensions {
/** A {@link Cleaner} handling freeing of memory for library objects. */
static final Cleaner CLEANER = Cleaner.create();
/** /**
* Hashes the given {@link String} using CodeMP's hashing algorithm (xxh3). * Hashes the given {@link String} using CodeMP's hashing algorithm (xxh3).
* @param input the string to hash * @param input the string to hash
@ -37,21 +40,7 @@ public final class Extensions {
*/ */
public static native void setupTracing(String path, boolean debug); public static native void setupTracing(String path, boolean debug);
private static boolean loaded = false;
static synchronized void loadLibraryIfNotPresent() {
if(loaded) return;
try {
String filename = System.getProperty("os.name").startsWith("Windows")
? "/natives/codemp.dll"
: "/natives/libcodemp.so";
cz.adamh.utils.NativeUtils.loadLibraryFromJar(filename);
loaded = true;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
static { static {
Extensions.loadLibraryIfNotPresent(); NativeUtils.loadLibraryIfNeeded();
} }
} }

160
dist/java/src/mp/code/NativeUtils.java vendored Normal file
View file

@ -0,0 +1,160 @@
/*
* Class NativeUtils is published under the The MIT License:
*
* Copyright (c) 2012 Adam Heinrich <adam@adamh.cz>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mp.code;
import java.io.*;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.ProviderNotFoundException;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
/**
* A simple library class which helps with loading dynamic libraries stored in the
* JAR archive. These libraries usually contain implementation of some methods in
* native code (using JNI - Java Native Interface).
* @see <a href="http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar">http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar</a>
* @see <a href="https://github.com/adamheinrich/native-utils">https://github.com/adamheinrich/native-utils</a>
*/
class NativeUtils {
/**
* The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
*/
private static final int MIN_PREFIX_LENGTH = 3;
/**
* Prefix of the temporary folder where the native is stored.
*/
public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils";
/**
* Temporary directory which will contain the DLLs.
*/
private static File temporaryDir;
/**
* Private constructor - this class will never be instanced
*/
private NativeUtils() {}
/**
* Loads library from current JAR archive.
* The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not system-dependent.
* @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters
* (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the JAR.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
private static void loadLibraryFromJar(String path) throws IOException {
if(null == path || !path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}
// Obtain filename from path
String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
// Check if the filename is okay
if(filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}
// Prepare temporary file
if(temporaryDir == null) {
temporaryDir = createTempDirectory();
temporaryDir.deleteOnExit();
}
File temp = new File(temporaryDir, filename);
try(InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(Objects.requireNonNull(is), temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
try {
System.load(temp.getAbsolutePath());
} finally {
if(isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
private static boolean isPosixCompliant() {
try {
return FileSystems.getDefault()
.supportedFileAttributeViews()
.contains("posix");
} catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) {
return false;
}
}
private static File createTempDirectory() throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
File generatedDir = new File(tempDir, NativeUtils.NATIVE_FOLDER_PATH_PREFIX + System.nanoTime());
if(!generatedDir.mkdir())
throw new IOException("Failed to create temp directory " + generatedDir.getName());
return generatedDir;
}
private static boolean loaded = false;
static synchronized void loadLibraryIfNeeded() {
if(loaded) return;
try {
String os = System.getProperty("os.name").toLowerCase();
String filename;
if(os.startsWith("windows")) {
filename = "/natives/codemp.dll";
} else if(os.startsWith("mac")) {
filename = "/natives/libcodemp.dylib";;
} else filename = "/natives/libcodemp.so";
loadLibraryFromJar(filename);
loaded = true;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}

View file

@ -21,6 +21,7 @@ public final class Workspace {
Workspace(long ptr) { Workspace(long ptr) {
this.ptr = ptr; this.ptr = ptr;
Extensions.CLEANER.register(this, () -> free(ptr));
} }
private static native String get_workspace_id(long self); private static native String get_workspace_id(long self);
@ -170,13 +171,9 @@ public final class Workspace {
} }
private static native void free(long self); private static native void free(long self);
@Override
protected void finalize() {
free(this.ptr);
}
static { static {
Extensions.loadLibraryIfNotPresent(); NativeUtils.loadLibraryIfNeeded();
} }
/** /**