diff --git a/.github/workflows/graalpy-script-debug.yml b/.github/workflows/graalpy-script-debug.yml new file mode 100644 index 0000000..4bf83cd --- /dev/null +++ b/.github/workflows/graalpy-script-debug.yml @@ -0,0 +1,34 @@ +name: Test GraalPy Scripts Guide +on: + push: + paths: + - 'graalpy/graalpy-scripts-debug/**' + - '.github/workflows/graalpy-scripts-debug.yml' + pull_request: + paths: + - 'graalpy/graalpy-scripts-debug/**' + - '.github/workflows/graalpy-scripts-debug.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + run: + name: 'graalpy-scripts-debug' + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '23.0.1' + distribution: 'graalvm' + github-token: ${{ secrets.GITHUB_TOKEN }} + cache: 'maven' + - name: Build, test, and run 'graalpy-scripts-debug' using Maven + run: | + cd graalpy/graalpy-scripts-debug + ./mvnw --no-transfer-progress test + - name: Build, test, and run 'graalpy-scripts-debug' using Gradle + run: | + cd graalpy/graalpy-scripts-debug + ./gradlew test diff --git a/graalpy/graalpy-scripts-debug-guide/.gitattributes b/graalpy/graalpy-scripts-debug-guide/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/graalpy/graalpy-scripts-debug-guide/.gitignore b/graalpy/graalpy-scripts-debug-guide/.gitignore new file mode 100644 index 0000000..9182639 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/.gitignore @@ -0,0 +1,11 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +# Ignore maven build output directory +target + +# Ignore JDTLS build directory +bin \ No newline at end of file diff --git a/graalpy/graalpy-scripts-debug-guide/.mvn/wrapper/maven-wrapper.properties b/graalpy/graalpy-scripts-debug-guide/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/graalpy/graalpy-scripts-debug-guide/.vscode/extensions.json b/graalpy/graalpy-scripts-debug-guide/.vscode/extensions.json new file mode 100644 index 0000000..d928963 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-python.python", + "vscjava.vscode-java-pack" + ] +} diff --git a/graalpy/graalpy-scripts-debug-guide/.vscode/launch.json b/graalpy/graalpy-scripts-debug-guide/.vscode/launch.json new file mode 100644 index 0000000..83e370b --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/.vscode/launch.json @@ -0,0 +1,8 @@ +{ + "configurations": [{ + "name": "GraalPy: Attach embedded", + "type": "debugpy", + "request": "attach", + "connect": { "host": "localhost", "port": 4711 }, + }] +} \ No newline at end of file diff --git a/graalpy/graalpy-scripts-debug-guide/README.md b/graalpy/graalpy-scripts-debug-guide/README.md new file mode 100644 index 0000000..88f93ed --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/README.md @@ -0,0 +1,244 @@ +# Using and Debugging Python Scripts in Java Applications using VSCode + +Simple, unpackaged Python scripts can be run and shipped with Java applications. +The [GraalVM Polyglot APIs](https://www.graalvm.org/latest/reference-manual/embed-languages/) make it easy to run scripts that are simply included in the Java resources. + +## 1. Getting Started + +In this guide, we will add a small Python script to calculate the similarity of two files to a JavaFX application: +![Screenshot of the app](screenshot.png) + +## 2. What you will need + +To complete this guide, you will need the following: + + * Some time on your hands + * A decent text editor or IDE + * A supported JDK[^1], preferably the latest [GraalVM JDK](https://graalvm.org/downloads/) + + [^1]: Oracle JDK 17 and OpenJDK 17 are supported with interpreter only for GraalPy, but JavaFX requires JDK 21 or newer. + GraalVM JDK 21, Oracle JDK 21, OpenJDK 21 and offer GraalPy [JIT compilation](https://www.graalvm.org/latest/reference-manual/embed-languages/#runtime-optimization-support). + Note: GraalVM for JDK 17 is **not supported** for GraalPy. + +## 3. Solution + +We encourage you to check out the [completed example](./) and follow with this guide step by step. + +## 4. Writing the application + +You can use either [Maven](https://openjfx.io/openjfx-docs/#maven) or [Gradle](https://openjfx.io/openjfx-docs/#gradle) to run the JavaFX example application. +We will demonstrate on both build systems. + +## 4.1 Dependency configuration + +We have added the required dependencies for GraalPy in the `` section of the POM or to the `dependencies` block in the `build.gradle.kts` file. + +`pom.xml` +```xml + + org.graalvm.polyglot + python + 24.1.1 + pom + + + org.graalvm.polyglot + polyglot + 24.1.1 + + + org.graalvm.tools + dap-tool + 24.1.1 + +``` + +`build.gradle.kts` +```kotlin +implementation("org.graalvm.polyglot:python:24.1.1") // ① +implementation("org.graalvm.polyglot:polyglot:24.1.1") // ③ +implementation("org.graalvm.tools:dap-tool:24.1.1") // ④ +``` + +❶ The `python` dependency is a meta-package that transitively depends on all resources and libraries to run GraalPy. + +❷ Note that the `python` package is not a JAR - it is simply a `pom` that declares more dependencies. + +❸ The `polyglot` dependency provides the APIs to manage and use GraalPy from Java. + +❹ The `dap` dependency provides a remote debugger for GraalPy that we can use when Python code is embedded in a Java application. + +## 4.2 Adding a Python script + +We can just include simple Python scripts in our resources source folder. +In this example, the script contains a function that uses the Python standard library to compute the similarity between two files. + +`src/main/resources/compare_files.py` +```python +import polyglot # pyright: ignore + +from difflib import SequenceMatcher +from os import PathLike + + +@polyglot.export_value # ① +def compare_files(a: PathLike, b: PathLike) -> float: + with open(a) as file_1, open(b) as file_2: + file1_data = file_1.read() + file2_data = file_2.read() + similarity_ratio = SequenceMatcher(None, file1_data, file2_data).ratio() + return similarity_ratio +``` + +❶ The only GraalPy-specific code here is this `polyglot.export_value` annotation, which makes the function accessible by name to the Java world. + +## 4.2.1 Working with GraalPy in VSCode + +You can use [pyenv](https://github.com/pyenv/pyenv) or [pyenv-win](https://github.com/pyenv-win/pyenv-win) with the [Python extensions](https://marketplace.visualstudio.com/items?itemName=ms-python.python) in VSCode to setup and use GraalPy during development. +You can than edit and debug your Python files using the standard Python tooling. + +![Gif animation of installing GraalPy with pyenv](./graalpy-vscode-pyenv.gif) +![Gif animation of using GraalPy in VSCode](./graalpy-vscode-select.gif) +![Gif animation of debugging with GraalPy in VSCode](./graalpy-vscode-debug.gif) + +## 4.3 Creating a Python context + +GraalVM provides Polyglot APIs to make starting a Python context easy. +We create the Python context in the JavaFX `start` method. +We also override the `stop` method to close the context and free any associated resources. + +`App.java` +```java +public class App extends Application { + private Context context; + + @Override + public void stop() throws Exception { + context.close(); + super.stop(); + } + + @Override + public void start(Stage stage) { + context = Context.newBuilder("python") + .allowIO(IOAccess.newBuilder() // ① + .fileSystem(FileSystem.newReadOnlyFileSystem(FileSystem.newDefaultFileSystem())) + .build()) + .allowPolyglotAccess(PolyglotAccess.newBuilder() // ② + .allowBindingsAccess("python") + .build()) + // These are all the options we need to run the app +``` + +❶ By default, GraalPy will be sandboxed completely, but our script wants to access files. +Read-only access is enough for this case, so we grant no more. + +❷ Our script exposes the `compare_files` function by name to the Java world. +We explicitly allow this as well. + +## 4.3 Calling the Python script from Java + +`App.java` +```java +try { + context.eval(Source.newBuilder("python", App.class.getResource("/compare_files.py")).build()); // ① +} catch (IOException e) { + throw new RuntimeException(e); +} +final Value compareFiles = context.getBindings("python").getMember("compare_files"); // ② + +target.setOnDragDropped((event) -> { + var success = false; + List files; + if ((files = event.getDragboard().getFiles()) != null && files.size() == 2) { + try { + File file0 = files.get(0), file1 = files.get(1); + var result = compareFiles.execute(file0.getAbsolutePath(), file1.getAbsolutePath()).asDouble(); // ③ + target.setText(String.format("%s = %f x %s", file0.getName(), result, file1.getName())); + success = true; + } catch (RuntimeException e) { + target.setText(e.getMessage()); + } + } + resetTargetColor(target); + event.setDropCompleted(success); + event.consume(); +}); +``` + +❶ We can pass a resource URL to the GraalVM Polyglot [`Source`](https://docs.oracle.com/en/graalvm/enterprise/20/sdk/org/graalvm/polyglot/Source.html) API. +The content is read by the `Source` object, GraalPy and the Python code do not gain access to Java resources this way. + +❷ Python objects are returned using a generic [`Value`](https://docs.oracle.com/en/graalvm/enterprise/20/sdk/org/graalvm/polyglot/Value.html) type. + +❸ As a Python function, `compare_files` can be executed. +GraalPy accepts Java objects and tries to match them to the appropriate Python types. +Return values are again represented as `Value`. +In this case we know the result will be a Python `float`, which can be converted to a Java `double`. + +## 5. Running the application + +If you followed along with the example, you can now compile and run your application from the commandline: + +With Maven: + +```shell +./mvnw compile +./mvnw javafx:run +``` + +With Gradle: + +```shell +./gradlew assemble +./gradlwe run +``` + +## 5.1 Debugging embedded Python code + +Your Python code may behave differently when run in a Java embedding. +This can have many reasons, from different types passed in from Java, permissions of the GraalVM Polyglot sandbox, to Python libraries assuming OS-specific process properties that Java applications do not expose. + +To debug Python scripts, we recommend you use VSCode. +Make sure you have installed the [Python extensions](https://marketplace.visualstudio.com/items?itemName=ms-python.python). +Where we build the Python context, we can add the following options to enable remote debugging: + +`App.java` +```java +.option("dap", "localhost:4711") +.option("dap.Suspend", "false") +``` + +This instructs the runtime to accept [DAP]() connections on port 4711 and continue execution. +We add a debug configuration to VSCode to match: + +`.vscode/launch.json` +```json +{ + "configurations": [{ + "name": "GraalPy: Attach embedded", + "type": "debugpy", + "request": "attach", + "connect": { "host": "localhost", "port": 4711 }, + }] +} +``` + +When we run the application now, we will see the following output: + +``` +[Graal DAP] Starting server and listening on localhost/127.0.0.1:4711 +``` + +We can connect using VSCode or any other DAP client. +The loaded sources can be opened to view the Python code as loaded from the Java resources. +We can set breakpoints and inspect runtime state as we would expect. + +![Gif animation debugging GraalPy in Java in VSCode](./graalpy-vscode-dap-debug.gif) + +## 6. Next steps + +- Use GraalPy with popular Java frameworks, such as [Spring Boot](../graalpy-spring-boot-guide/README.md) or [Micronaut](../graalpy-micronaut-guide/README.md) +- [Migrate from Jython](../graalpy-jython-guide/README.md) to GraalPy +- Learn more about the Polyglot API for [embedding languages](https://www.graalvm.org/latest/reference-manual/embed-languages/) +- Explore in depth with GraalPy [reference manual](https://www.graalvm.org/latest/reference-manual/python/) diff --git a/graalpy/graalpy-scripts-debug-guide/build.gradle.kts b/graalpy/graalpy-scripts-debug-guide/build.gradle.kts new file mode 100644 index 0000000..630c568 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/build.gradle.kts @@ -0,0 +1,35 @@ +plugins { + application; + id("org.openjfx.javafxplugin") version "0.1.0" +} + +javafx { + version = "23.0.1" + modules = listOf("javafx.controls") +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + implementation("org.graalvm.polyglot:python:24.1.1") // ① + implementation("org.graalvm.polyglot:polyglot:24.1.1") // ③ + implementation("org.graalvm.tools:dap-tool:24.1.1") // ④ + + // Use JUnit Jupiter for testing. + testImplementation("org.junit.jupiter:junit-jupiter:5.11.0") + + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +application { + // Define the main class for the application. + mainClass = "com.example.App" +} + +tasks.named("test") { + // Use JUnit Platform for unit tests. + useJUnitPlatform() +} diff --git a/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-dap-debug.gif b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-dap-debug.gif new file mode 100644 index 0000000..cc51cc0 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-dap-debug.gif differ diff --git a/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-debug.gif b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-debug.gif new file mode 100644 index 0000000..3f743a6 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-debug.gif differ diff --git a/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pip-install.gif b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pip-install.gif new file mode 100644 index 0000000..2740a4d Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pip-install.gif differ diff --git a/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pyenv.gif b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pyenv.gif new file mode 100644 index 0000000..ffa7c26 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-pyenv.gif differ diff --git a/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-select.gif b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-select.gif new file mode 100644 index 0000000..b5abc75 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/graalpy-vscode-select.gif differ diff --git a/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.jar b/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.jar differ diff --git a/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.properties b/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0aaefbc --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/graalpy/graalpy-scripts-debug-guide/gradlew b/graalpy/graalpy-scripts-debug-guide/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/gradlew @@ -0,0 +1,252 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/HEAD/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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/graalpy/graalpy-scripts-debug-guide/gradlew.bat b/graalpy/graalpy-scripts-debug-guide/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/graalpy/graalpy-scripts-debug-guide/mvnw b/graalpy/graalpy-scripts-debug-guide/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/graalpy/graalpy-scripts-debug-guide/mvnw.cmd b/graalpy/graalpy-scripts-debug-guide/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/graalpy/graalpy-scripts-debug-guide/pom.xml b/graalpy/graalpy-scripts-debug-guide/pom.xml new file mode 100644 index 0000000..ae39618 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/pom.xml @@ -0,0 +1,141 @@ + + + 4.0.0 + + com.example + demo + 1.0-SNAPSHOT + + demo + + http://www.example.com + + + UTF-8 + 21 + + + + + + org.junit + junit-bom + 5.11.0 + pom + import + + + + + + + org.graalvm.polyglot + python + 24.1.1 + pom + + + org.graalvm.polyglot + polyglot + 24.1.1 + + + org.graalvm.tools + dap-tool + 24.1.1 + + + + org.openjfx + javafx-controls + 23.0.1 + + + + org.junit.jupiter + junit-jupiter-api + test + + + + org.junit.jupiter + junit-jupiter-params + test + + + + + + + + + org.openjfx + javafx-maven-plugin + 0.0.8 + + com.example.App + + + + + maven-clean-plugin + 3.4.0 + + + + maven-resources-plugin + 3.3.1 + + + maven-compiler-plugin + 3.13.0 + + + maven-surefire-plugin + 3.3.0 + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + + java + + + + + com.example.App + + + + maven-jar-plugin + 3.4.2 + + + maven-install-plugin + 3.1.2 + + + maven-deploy-plugin + 3.1.2 + + + + maven-site-plugin + 3.12.1 + + + maven-project-info-reports-plugin + 3.6.1 + + + + + + + + + diff --git a/graalpy/graalpy-scripts-debug-guide/screenshot.png b/graalpy/graalpy-scripts-debug-guide/screenshot.png new file mode 100644 index 0000000..72f59c2 Binary files /dev/null and b/graalpy/graalpy-scripts-debug-guide/screenshot.png differ diff --git a/graalpy/graalpy-scripts-debug-guide/settings.gradle.kts b/graalpy/graalpy-scripts-debug-guide/settings.gradle.kts new file mode 100644 index 0000000..0754fa9 --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "graalpy-python-script-embedding" diff --git a/graalpy/graalpy-scripts-debug-guide/src/main/java/com/example/App.java b/graalpy/graalpy-scripts-debug-guide/src/main/java/com/example/App.java new file mode 100644 index 0000000..979648d --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/src/main/java/com/example/App.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. + * All rights reserved. Use is subject to license terms. + * + * This file is available and licensed under the following license: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.example; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.graalvm.polyglot.Context; +import org.graalvm.polyglot.PolyglotAccess; +import org.graalvm.polyglot.PolyglotException; +import org.graalvm.polyglot.Source; +import org.graalvm.polyglot.Value; +import org.graalvm.polyglot.io.FileSystem; +import org.graalvm.polyglot.io.IOAccess; + +import javafx.application.Application; +import javafx.geometry.Insets; +import javafx.scene.Scene; +import javafx.scene.input.TransferMode; +import javafx.scene.layout.StackPane; +import javafx.scene.paint.Color; +import javafx.scene.text.Text; +import javafx.scene.text.TextAlignment; +import javafx.stage.Stage; + +public class App extends Application { + private Context context; + + @Override + public void stop() throws Exception { + context.close(); + super.stop(); + } + + @Override + public void start(Stage stage) { + context = Context.newBuilder("python") + .allowIO(IOAccess.newBuilder() // ① + .fileSystem(FileSystem.newReadOnlyFileSystem(FileSystem.newDefaultFileSystem())) + .build()) + .allowPolyglotAccess(PolyglotAccess.newBuilder() // ② + .allowBindingsAccess("python") + .build()) + // These are all the options we need to run the app + .option("dap", "localhost:4711") + .option("dap.Suspend", "false") + .build(); + + stage.setTitle("Similarity score"); + + var root = new StackPane(); + var scene = new Scene(root, 800, 200); + + final var target = new Text(200, 100, "DROP FILES HERE"); + target.setTextAlignment(TextAlignment.CENTER); + resetTargetColor(target); + target.setScaleX(2.0); + target.setScaleY(2.0); + StackPane.setMargin(target, new Insets(10, 10, 10, 10)); + + target.setOnDragOver((event) -> { + if (event.getGestureSource() != target && event.getDragboard().hasFiles()) { + event.acceptTransferModes(TransferMode.ANY); + } + event.consume(); + } + ); + + target.setOnDragEntered((event) -> { + var dragboard = event.getDragboard(); + if (event.getGestureSource() != target && dragboard.hasFiles() && dragboard.getFiles().size() == 2) { + target.setFill(Color.GREEN); + } else { + target.setText("Drop 2 files to compare."); + } + event.consume(); + } + ); + + target.setOnDragExited((event) -> { + resetTargetColor(target); + event.consume(); + }); + + try { + context.eval(Source.newBuilder("python", App.class.getResource("/compare_files.py")).build()); // ① + } catch (IOException e) { + throw new RuntimeException(e); + } + final Value compareFiles = context.getBindings("python").getMember("compare_files"); // ② + + target.setOnDragDropped((event) -> { + var success = false; + List files; + if ((files = event.getDragboard().getFiles()) != null && files.size() == 2) { + try { + File file0 = files.get(0), file1 = files.get(1); + var result = compareFiles.execute(file0.getAbsolutePath(), file1.getAbsolutePath()).asDouble(); // ③ + target.setText(String.format("%s = %f x %s", file0.getName(), result, file1.getName())); + success = true; + } catch (RuntimeException e) { + target.setText(e.getMessage()); + } + } + resetTargetColor(target); + event.setDropCompleted(success); + event.consume(); + }); + + root.getChildren().add(target); + stage.setScene(scene); + + stage.show(); + + if (getParameters().getRaw().contains("CI")) { + stage.close(); + } + } + + private static void resetTargetColor(final Text target) { + target.setFill(Color.LIGHTGRAY); + } + + public static void main(String[] args) { + Application.launch(args); + } +} diff --git a/graalpy/graalpy-scripts-debug-guide/src/main/resources/compare_files.py b/graalpy/graalpy-scripts-debug-guide/src/main/resources/compare_files.py new file mode 100644 index 0000000..8ca422a --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/src/main/resources/compare_files.py @@ -0,0 +1,13 @@ +import polyglot # pyright: ignore + +from difflib import SequenceMatcher +from os import PathLike + + +@polyglot.export_value # ① +def compare_files(a: PathLike, b: PathLike) -> float: + with open(a) as file_1, open(b) as file_2: + file1_data = file_1.read() + file2_data = file_2.read() + similarity_ratio = SequenceMatcher(None, file1_data, file2_data).ratio() + return similarity_ratio diff --git a/graalpy/graalpy-scripts-debug-guide/src/test/java/com/example/AppTest.java b/graalpy/graalpy-scripts-debug-guide/src/test/java/com/example/AppTest.java new file mode 100644 index 0000000..9bcfaae --- /dev/null +++ b/graalpy/graalpy-scripts-debug-guide/src/test/java/com/example/AppTest.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. + * + * Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.org/license/UPL. + */ + +package com.example; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +class AppTest { + @Test + void appRuns() { + assertDoesNotThrow(() -> App.main(new String[]{"CI"})); + } +}