diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7958061 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,42 @@ +name: CI + +on: [push] + +jobs: + test: + name: Build and test the plugin + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + JAVA_VERSION: [8, 11, 17, 21] + + steps: + - uses: actions/checkout@v4 + with: + submodules: 'true' + + - name: Setup Java ${{ matrix.JAVA_VERSION }} + uses: actions/setup-java@v3 + with: + java-version: ${{matrix.JAVA_VERSION}} + architecture: x64 + distribution: adopt + + - name: Compile + run: | + make clean + make check + make compile + make compile-with-nextflow + + - name: Build + run: make build + + - name: Install + run: make install-local + + - name: Test + run: make test + env: + GRADLE_OPTS: '-Dorg.gradle.daemon=false' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eb0a0c --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +.gradle +.idea +.nextflow* +build/ +out/ +work/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..b20225a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "nextflow"] + path = nextflow + url = git@github.com:nextflow-io/nextflow.git diff --git a/LICENSE b/LICENSE index 840b249..1a8ce46 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 Fulcrum Genomics +Copyright © 2023 Fulcrum Genomics LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +19,179 @@ 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. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..79b01a2 --- /dev/null +++ b/Makefile @@ -0,0 +1,38 @@ +version ?= $(shell grep 'Plugin-Version' plugins/nf-dotenv/src/resources/META-INF/MANIFEST.MF | awk '{ print $$2 }') + +.PHONY: check +check: + ./gradlew check --warning-mode all + +.PHONY: clean +clean: + ./gradlew clean + +.PHONY: compile +compile: + ./gradlew compileGroovy + +.PHONY: compile-with-nextflow +compile-with-nextflow: + grep -qxF 'includeBuild("nextflow")' settings.gradle || echo 'includeBuild("nextflow")' >> settings.gradle + ./gradlew :nextflow:exportClasspath assemble + sed -i.backup '/includeBuild("nextflow")/d' settings.gradle + rm -f settings.gradle.backup + +.PHONY: test +test: + ./gradlew :plugins:nf-dotenv:test --warning-mode all + +.PHONY: build +build: + ./gradlew copyPluginZip + +.PHONY: install-local +install-local: build + mkdir -p ${HOME}/.nextflow/plugins/ + rm -rf ${HOME}/.nextflow/plugins/nf-dotenv-${version} + cp -r build/plugins/nf-dotenv-${version} ${HOME}/.nextflow/plugins/nf-dotenv-${version} + +.POHNY: publish-to-github +publish-to-github: + ./gradlew plugins:upload diff --git a/README.md b/README.md new file mode 100644 index 0000000..d5fca39 --- /dev/null +++ b/README.md @@ -0,0 +1,157 @@ +# nf-dotenv + +[![CI](https://github.com/fulcrumgenomics/nf-dotenv/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/fulcrumgenomics/nf-dotenv/actions/workflows/test.yml?query=branch%3Amain) +[![Nextflow](https://img.shields.io/badge/Nextflow%20DSL2-%E2%89%A522.10.0-blue.svg)](https://www.nextflow.io/) +[![Java Versions](https://img.shields.io/badge/java-8_|_11_|_17_|_21-blue)](https://github.com/fulcrumgenomics/nf-dotenv) + +Automatically source [dotenv](https://hexdocs.pm/dotenvy/dotenv-file-format.html) files into your Nextflow scope. + +## Quickstart + +Add the plugin to your Nextflow config: + +```nextflow +plugins { id 'nf-dotenv' } +``` + +And add the following import statement into your processes and workflow files: + +```nextflow +include { dotenv } from "plugin/nf-dotenv" +``` + +Now you're ready to source environmental file variables in Nextflow contexts! + +```nextflow +dotenv("KeyFromEnvironment") +``` + +## Configuration + +This plugin support the following Nextflow configuration: + +```nextflow +dotenv.filename = ".env" // Filename of the dotenv file +dotenv.relative = "." // Relative path of the dotenv file to the main script +``` + +## A Real World Example + +Let's say you have the following Nextflow project: + +#### Dotenv (`.env`) + +```ini +SAMTOOLS_VERSION=1.17 +``` +#### Docker Image (`Dockerfile`) + +```dockerfile +FROM alpine:3.18 + +RUN apk add --update --no-cache \ + bash=5.2.15-r5 \ + build-base=0.5-r3 \ + bzip2-dev=1.0.8-r5 \ + xz-dev=5.4.3-r0 \ + zlib-dev=1.2.13-r1 + +ARG SAMTOOLS_VERSION + +RUN wget https://github.com/samtools/samtools/releases/download/${SAMTOOLS_VERSION}/samtools-${SAMTOOLS_VERSION}.tar.bz2 \ + && tar -xjvf samtools-${SAMTOOLS_VERSION}.tar.bz2 \ + && cd samtools-${SAMTOOLS_VERSION} \ + && ./configure --without-curses --enable-configure-htslib \ + && make all all-htslib -j 8 \ + && make install install-htslib \ + && rm -r ../samtools-${SAMTOOLS_VERSION} +``` + +#### Docker Compose (`docker-compose.yaml`) + +```yaml +services: + samtools: + build: + args: + SAMTOOLS_VERSION: ${SAMTOOLS_VERSION} + tags: ['samtools:${SAMTOOLS_VERSION}'] +``` + +#### Nextflow Script (`main.nf`) + +```nextflow +include { dotenv } from "plugin/nf-dotenv" + +process emit_samtools_version { + container "samtools:${dotenv('SAMTOOLS_VERSION')}" + output: stdout + + """ + samtools --version | head -n1 + """ +} + +workflow { emit_samtools_version() | view } +``` + +After building the Docker image with `docker compose build`, and after [enabling Docker for Nextflow](https://www.nextflow.io/docs/latest/docker.html#how-it-works), you will be able to use `nf-dotenv` to source the version tag of the container to use in your Nextflow process. +When the main Nextflow script is run with `nextflow run main.nf`, you will get the following output: + +```console +❯ nextflow --quiet run main.nf +samtools 1.17 +``` + +However, upgrade the dotenv variable `SAMTOOLS_VERSION` to `1.18` and you'll see: + +```console +❯ nextflow --quiet run main.nf +samtools 1.18 +``` + +Conveniently for debugging, local environment variables take precedence over dotenv variables: + +```console +❯ SAMTOOLS_VERSION=1.16 nextflow --quiet run main.nf +samtools 1.16 +``` + +## Testing the Plugin Locally + +Execute the following to check, compile, and run unit tests for the plugin: + +``` +make check +make compile +make test +``` + +To install the plugin for use in local workflows (_e.g._ not internet connected), execute the following: + +``` +make install-local +``` + +## Developing the Plugin Locally + + +Execute the following to build the plugin along with Nextflow source files: + +``` +make compile-with-nextflow +``` + +Test your changes to the plugin on a Nextflow script like: + +```bash +NXF_PLUGINS_DEV="${PWD}/plugins" nextflow/launch.sh run -plugins nf-dotenv +``` + +## Publishing to GitHub + +After bumping the version of the plugin in the file [`MANIFEST.MF`](./plugins/nf-dotenv/src/resources/META-INF/MANIFEST.MF), execute the following: + +``` +GITHUB_TOKEN=... GITHUB_USERNAME=... GITHUB_COMMIT_EMAIL=... make publish-to-github +``` diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000..4fa76d0 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,7 @@ +plugins { + id 'groovy-gradle-plugin' +} + +repositories { + gradlePluginPortal() +} diff --git a/buildSrc/src/main/groovy/io.nextflow.groovy-application-conventions.gradle b/buildSrc/src/main/groovy/io.nextflow.groovy-application-conventions.gradle new file mode 100644 index 0000000..a64d74f --- /dev/null +++ b/buildSrc/src/main/groovy/io.nextflow.groovy-application-conventions.gradle @@ -0,0 +1,4 @@ +plugins { + id 'io.nextflow.groovy-common-conventions' + id 'application' +} diff --git a/buildSrc/src/main/groovy/io.nextflow.groovy-common-conventions.gradle b/buildSrc/src/main/groovy/io.nextflow.groovy-common-conventions.gradle new file mode 100644 index 0000000..e588935 --- /dev/null +++ b/buildSrc/src/main/groovy/io.nextflow.groovy-common-conventions.gradle @@ -0,0 +1,42 @@ +plugins { + id 'groovy' +} + +repositories { + mavenCentral() +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(19) + } +} + +compileJava { + options.release.set(11) +} + +tasks.withType(GroovyCompile) { + sourceCompatibility = '11' + targetCompatibility = '11' +} + +tasks.withType(Test) { + jvmArgs ([ + '--add-opens=java.base/java.lang=ALL-UNNAMED', + '--add-opens=java.base/java.io=ALL-UNNAMED', + '--add-opens=java.base/java.nio=ALL-UNNAMED', + '--add-opens=java.base/java.nio.file.spi=ALL-UNNAMED', + '--add-opens=java.base/java.net=ALL-UNNAMED', + '--add-opens=java.base/java.util=ALL-UNNAMED', + '--add-opens=java.base/java.util.concurrent.locks=ALL-UNNAMED', + '--add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED', + '--add-opens=java.base/sun.nio.ch=ALL-UNNAMED', + '--add-opens=java.base/sun.nio.fs=ALL-UNNAMED', + '--add-opens=java.base/sun.net.www.protocol.http=ALL-UNNAMED', + '--add-opens=java.base/sun.net.www.protocol.https=ALL-UNNAMED', + '--add-opens=java.base/sun.net.www.protocol.ftp=ALL-UNNAMED', + '--add-opens=java.base/sun.net.www.protocol.file=ALL-UNNAMED', + '--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED', + ]) +} diff --git a/buildSrc/src/main/groovy/io.nextflow.groovy-library-conventions.gradle b/buildSrc/src/main/groovy/io.nextflow.groovy-library-conventions.gradle new file mode 100644 index 0000000..794b370 --- /dev/null +++ b/buildSrc/src/main/groovy/io.nextflow.groovy-library-conventions.gradle @@ -0,0 +1,4 @@ +plugins { + id 'io.nextflow.groovy-common-conventions' + id 'java-library' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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/HEAD/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 + +# 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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/nextflow b/nextflow new file mode 160000 index 0000000..d49f02a --- /dev/null +++ b/nextflow @@ -0,0 +1 @@ +Subproject commit d49f02aeb4c44287f64b2df7a5d25a5a073581f8 diff --git a/plugins/build.gradle b/plugins/build.gradle new file mode 100644 index 0000000..83c45af --- /dev/null +++ b/plugins/build.gradle @@ -0,0 +1,171 @@ +/* Copyright 2021-2022, Seqera Labs + * + * 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 + * + * 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. + */ + +import io.nextflow.gradle.tasks.GithubRepositoryPublisher +import io.nextflow.gradle.tasks.GithubUploader +import org.apache.commons.codec.digest.DigestUtils + +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +plugins { + id "java" + id "io.nextflow.nf-build-plugin" version "1.0.1" +} + +ext.github_organization = project.findProperty('github_organization') ?: 'fulcrumgenomics' +ext.github_access_token = project.findProperty('github_access_token') ?: System.getenv('GITHUB_TOKEN') +ext.github_username = project.findProperty('github_username') ?: System.getenv('GITHUB_USERNAME') +ext.github_commit_email = project.findProperty('github_commit_email') ?: System.getenv('GITHUB_COMMIT_EMAIL') + +jar.enabled = false + +static String computeSha512(File file) { + if (!file.exists()) + throw new GradleException("Missing file: $file -- cannot compute SHA-512") + return DigestUtils.sha512Hex(file.bytes) +} + +String now() { + "${OffsetDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)}" +} + +List allPlugins() { + def plugins = [] + new File(rootProject.rootDir, 'plugins') .eachDir { if(it.name.startsWith('nf-')) plugins.add(it.name) } + return plugins +} + +static String metaFromManifest(String meta, File file) { + def str = file.text + def regex = ~/(?m)^$meta:\s*([\w-\.<>=]+)$/ + def m = regex.matcher(str) + if (m.find()) { + def ver = m.group(1) + return ver + } + throw new GradleException("Cannot find '$meta' for plugin: $file") +} + +def timestamp = now() + +subprojects { + apply plugin: 'java' + apply plugin: 'groovy' + apply plugin: 'io.nextflow.nf-build-plugin' + + repositories { + mavenLocal() + mavenCentral() + } + + version = metaFromManifest('Plugin-Version',file('src/resources/META-INF/MANIFEST.MF')) + + tasks.withType(Jar).configureEach { + duplicatesStrategy = DuplicatesStrategy.INCLUDE + } + + /** Create the plugin ZIP and JSON metadata files in the plugin `build/libs` directory. */ + tasks.register('makeZip', Jar) { + into('classes') { with jar } + into('lib') { from configurations.runtimeClasspath } + manifest.from file('src/resources/META-INF/MANIFEST.MF') + archiveExtension = 'zip' + preserveFileTimestamps = false + reproducibleFileOrder = true + + doLast { + final zip = new File("$buildDir/libs/${project.name}-${project.version}.zip") + final json = new File("$buildDir/libs/${project.name}-${project.version}-meta.json") + json.text = """\ + { + "version": "${project.version}", + "date": "${timestamp}", + "url": "https://github.com/${github_organization}/${project.name}/releases/download/${project.version}/${project.name}-${project.version}.zip", + "requires": "${metaFromManifest('Plugin-Requires', file('src/resources/META-INF/MANIFEST.MF'))}", + "sha512sum": "${computeSha512(zip)}" + } + """.stripIndent() + file("$buildDir/tmp/makeZip").deleteDir() + } + outputs.file("$buildDir/libs/${project.name}-${project.version}.zip") + } + + /** Copy the plugin dependencies into the subproject `build/target/libs` directory. */ + tasks.register('copyPluginLibs', Sync) { + from configurations.runtimeClasspath + into 'build/target/libs' + } + + /** Copy the plugin into the project root build/plugins directory. */ + tasks.register('copyPluginZip', Copy) { + dependsOn project.tasks.findByName('makeZip') + from makeZip + into "$rootProject.buildDir/plugins" + outputs.file("$rootProject.buildDir/plugins/${project.name}-${project.version}.zip") + doLast { + ant.unzip( + src: "$rootProject.buildDir/plugins/${project.name}-${project.version}.zip", + dest: "$rootProject.buildDir/plugins/${project.name}-${project.version}" + ) + } + } + + /** "Install" the plugin into the project root build/plugins directory. */ + project.parent.tasks.getByName("assemble").dependsOn << copyPluginZip + + tasks.register('uploadPlugin', GithubUploader) { + dependsOn makeZip + assets = providers.provider { + ["$buildDir/libs/${project.name}-${project.version}.zip", + "$buildDir/libs/${project.name}-${project.version}-meta.json"] + } + release = providers.provider { project.version } + repo = providers.provider { project.name } + owner = github_organization + userName = github_username + authToken = github_access_token + skipExisting = true + } + + jar { + from sourceSets.main.allSource + doLast { + file("$buildDir/tmp/jar").deleteDir() + } + } + + tasks.withType(GenerateModuleMetadata).configureEach { + enabled = false + } + + task upload(dependsOn: [uploadPlugin] ) { } +} + +/** Upload all plugins to the corresponding GitHub repos. */ +task upload(dependsOn: [subprojects.uploadPlugin]) { } + +/** Copy the plugins required dependencies in the corresponding lib directory. */ +classes.dependsOn subprojects.copyPluginLibs + +/** Merge and publish the plugins index files. */ +task publishIndex( type: GithubRepositoryPublisher ) { + indexUrl = 'https://github.com/nextflow-io/plugins/main/plugins.json' + repos = allPlugins() + owner = github_organization + githubUser = github_username + githubEmail = github_commit_email + githubToken = github_access_token +} diff --git a/plugins/nf-dotenv/build.gradle b/plugins/nf-dotenv/build.gradle new file mode 100644 index 0000000..7635675 --- /dev/null +++ b/plugins/nf-dotenv/build.gradle @@ -0,0 +1,85 @@ +/* Copyright 2021-2022, Seqera Labs + * + * 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 + * + * 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. + */ + +plugins { + // TODO: Figure out how to build all this for cross-Java support without needing ./buildSrc! + id 'io.nextflow.groovy-library-conventions' + id 'idea' +} + +group = 'io.nextflow' + +idea { + module.inheritOutputDirs = true +} + +repositories { + mavenCentral() + maven { url = 'https://jitpack.io' } + maven { url = 'https://s3-eu-west-1.amazonaws.com/maven.seqera.io/releases' } + maven { url = 'https://s3-eu-west-1.amazonaws.com/maven.seqera.io/snapshots' } +} + +configurations { + // See https://docs.gradle.org/4.1/userguide/dependency_management.html#sub:exclude_transitive_dependencies + runtimeClasspath.exclude group: 'org.slf4j', module: 'slf4j-api' +} + +sourceSets { + main.java.srcDirs = [] + main.groovy.srcDirs = ['src/main'] + main.resources.srcDirs = ['src/resources'] + test.groovy.srcDirs = ['src/test'] + test.java.srcDirs = [] + test.resources.srcDirs = ['src/testResources'] +} + +ext { + nextflowVersion = '23.04.0' +} + +dependencies { + // This dependency is exported to consumers, that is to say, it is found on their compile classpath. + compileOnly "io.nextflow:nextflow:$nextflowVersion" + compileOnly 'org.slf4j:slf4j-api:2.0.9' + compileOnly 'org.pf4j:pf4j:3.10.0' + + // Plugin dependencies. + implementation 'io.github.cdimascio:dotenv-java:3.0.0' + + // Test configuration. + testImplementation "org.codehaus.groovy:groovy:3.0.19" + testImplementation "org.codehaus.groovy:groovy-nio:3.0.19" + testImplementation "io.nextflow:nextflow:$nextflowVersion" + testImplementation ("org.codehaus.groovy:groovy-test:3.0.19") { exclude group: 'org.codehaus.groovy' } + testImplementation ("cglib:cglib-nodep:3.3.0") + testImplementation ("org.objenesis:objenesis:3.3") + testImplementation ("org.spockframework:spock-core:2.3-groovy-3.0") { exclude group: 'org.codehaus.groovy'; exclude group: 'net.bytebuddy' } + testImplementation ('org.spockframework:spock-junit4:2.3-groovy-3.0') { exclude group: 'org.codehaus.groovy'; exclude group: 'net.bytebuddy' } + testImplementation ('com.google.jimfs:jimfs:1.3.0') + + testImplementation(testFixtures("io.nextflow:nextflow:$nextflowVersion")) + testImplementation(testFixtures("io.nextflow:nf-commons:$nextflowVersion")) + + // See https://docs.gradle.org/4.1/userguide/dependency_management.html#sec:module_replacement + modules { + module("commons-logging:commons-logging") { replacedBy("org.slf4j:jcl-over-slf4j") } + } +} + +// Use the JUnit 5 testing platform +test { + useJUnitPlatform() +} diff --git a/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvExtension.groovy b/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvExtension.groovy new file mode 100644 index 0000000..fdea602 --- /dev/null +++ b/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvExtension.groovy @@ -0,0 +1,44 @@ +package nextflow.dotenv + +import groovy.transform.CompileStatic +import io.github.cdimascio.dotenv.Dotenv +import io.github.cdimascio.dotenv.DotenvBuilder +import nextflow.Session +import nextflow.plugin.extension.Function +import nextflow.plugin.extension.PluginExtensionPoint + +/** An extension to make dotenv file variables available to Nextflow scripts through a function call. */ +@CompileStatic +class DotenvExtension extends PluginExtensionPoint { + + /** The default filename for the dotenv file. */ + static final String DEFAULT_FILENAME = ".env" + + /** The configuration of this Nextflow session. */ + private Map config + + /** The dotenv environment result for this Nextflow session. */ + private Dotenv dotenv + + /** The default value to return when none is found in the environmental configuration file. */ + private String defaultValue + + /** Initializes the plugin once it is loaded and the session is ready. */ + @Override + protected void init(Session session) { + this.config = session.config.navigate('dotenv', [:]) as Map + this.defaultValue = config.get("default", "").toString() + this.dotenv = new DotenvBuilder() + // The filename of the dotenv file which is typically '.env' but could be '.envrc' or other + .filename(config.get("filename", DEFAULT_FILENAME).toString()) + // The relative directory to the main Nextflow script. + .directory(config.get("relative", session.baseDir.toUriString()).toString()) + .load() + } + + /** Return a value in the dotenv environment, or an empty string if the key is missing. */ + @Function + String dotenv(String key) { + this.dotenv.get(key, this.defaultValue).toString() + } +} diff --git a/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvPlugin.groovy b/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvPlugin.groovy new file mode 100644 index 0000000..46c4f27 --- /dev/null +++ b/plugins/nf-dotenv/src/main/nextflow/dotenv/DotenvPlugin.groovy @@ -0,0 +1,14 @@ +package nextflow.dotenv + +import groovy.transform.CompileStatic +import nextflow.plugin.BasePlugin +import org.pf4j.PluginWrapper + +/** The nf-dotenv Nextflow plugin entrypoint. */ +@CompileStatic +class DotenvPlugin extends BasePlugin { + + DotenvPlugin(PluginWrapper wrapper) { + super(wrapper) + } +} diff --git a/plugins/nf-dotenv/src/resources/META-INF/MANIFEST.MF b/plugins/nf-dotenv/src/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000..1968e21 --- /dev/null +++ b/plugins/nf-dotenv/src/resources/META-INF/MANIFEST.MF @@ -0,0 +1,6 @@ +Manifest-Version: 1.0 +Plugin-Id: nf-dotenv +Plugin-Version: 0.0.1 +Plugin-Class: nextflow.dotenv.DotenvPlugin +Plugin-Provider: nextflow +Plugin-Requires: >=22.10.0 diff --git a/plugins/nf-dotenv/src/resources/META-INF/extensions.idx b/plugins/nf-dotenv/src/resources/META-INF/extensions.idx new file mode 100644 index 0000000..2e80149 --- /dev/null +++ b/plugins/nf-dotenv/src/resources/META-INF/extensions.idx @@ -0,0 +1 @@ +nextflow.dotenv.DotenvExtension diff --git a/plugins/nf-dotenv/src/test/nextflow/dotenv/DotenvTest.groovy b/plugins/nf-dotenv/src/test/nextflow/dotenv/DotenvTest.groovy new file mode 100644 index 0000000..43b3e3d --- /dev/null +++ b/plugins/nf-dotenv/src/test/nextflow/dotenv/DotenvTest.groovy @@ -0,0 +1,201 @@ +package nextflow.dotenv + +import io.github.cdimascio.dotenv.DotenvException +import nextflow.Channel +import nextflow.plugin.Plugins +import nextflow.plugin.TestPluginDescriptorFinder +import nextflow.plugin.TestPluginManager +import nextflow.plugin.extension.PluginExtensionProvider +import org.pf4j.PluginDescriptorFinder +import spock.lang.Shared +import test.Dsl2Spec + +import java.nio.file.Path + +/** Unit tests for the nf-dotenv plugin that use virtual file systems and mocking to run. */ +class DotenvTest extends Dsl2Spec{ + + /** Share the plugin mode across all features in this specification. */ + @Shared String pluginsMode + + /** Setup the test class by loading all plugins. */ + def setup() { + PluginExtensionProvider.reset() + pluginsMode = System.getProperty('pf4j.mode') + System.setProperty('pf4j.mode', 'dev') + Path root = Path.of('.').toAbsolutePath().normalize() + def manager = new TestPluginManager(root) { + @Override + protected PluginDescriptorFinder createPluginDescriptorFinder() { + return new TestPluginDescriptorFinder() { + @Override + protected Path getManifestPath(Path pluginPath) { + return pluginPath.resolve('build/resources/main/META-INF/MANIFEST.MF') + } + } + } + } + Plugins.init(root, 'dev', manager) + } + + /** Cleanup the test class by unloading and resetting all plugins. */ + def cleanup() { + Plugins.stop() + PluginExtensionProvider.reset() + pluginsMode ? System.setProperty('pf4j.mode',pluginsMode) : System.clearProperty('pf4j.mode') + } + + def 'should have the plugin installed but not imported and raise no exception if a dotenv is not found' () { + when: + String SCRIPT= ''' + channel.of('hi-mom') + ''' + and: + def result = new MockScriptRunner([:]).setScript(SCRIPT).execute() + then: + result.val == 'hi-mom' + result.val == Channel.STOP + } + + def 'should import the plugin and raise an exception if a dotenv is not found' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of('hi-mom') + ''' + and: + new MockScriptRunner([:]).setScript(SCRIPT).execute() + then: + thrown DotenvException + } + + def 'should import the plugin and raise no exceptions the dotenv is found' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of('hi-mom') + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner([:]).setScript(SCRIPT).setDotenv(DOTENV).execute() + then: + result.val == 'hi-mom' + result.val == Channel.STOP + } + + def 'should import the plugin and return an empty value for a key that does not exist' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('BAZ')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner([:]).setScript(SCRIPT).setDotenv(DOTENV).execute() + then: + result.val == '' + result.val == Channel.STOP + } + + + def 'should import the plugin and return a the correct value for a key that does exist' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('FOO')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner([:]).setScript(SCRIPT).setDotenv(DOTENV).execute() + then: + result.val == 'bar' + result.val == Channel.STOP + } + + + def 'should import the plugin and allow for an override of the dotenv filename relative to the main script' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('FOO')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner(['dotenv.filename': '.envrc']) + .setScript(SCRIPT) + .setDotenv(DOTENV, '.envrc') + .execute() + then: + result.val == 'bar' + result.val == Channel.STOP + } + + + def 'should import the plugin and allow for an override of the dotenv directory as a child directory to the main script' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('FOO')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner(['dotenv.relative': 'test']) + .setScript(SCRIPT) + .setDotenv(DOTENV, DotenvExtension.DEFAULT_FILENAME, 'test') + .execute() + then: + result.val == 'bar' + result.val == Channel.STOP + } + + def 'should import the plugin and allow for an override of the dotenv directory as a parent directory to the main script' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('FOO')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner(['dotenv.relative': '../other']) + .setScript(SCRIPT) + .setDotenv(DOTENV, DotenvExtension.DEFAULT_FILENAME, '../other') + .execute() + then: + result.val == 'bar' + result.val == Channel.STOP + } + + def 'should import the plugin and allow for an override of the dotenv directory as the same as the env file' () { + when: + String SCRIPT = ''' + include { dotenv } from 'plugin/nf-dotenv' + channel.of(dotenv('FOO')) + ''' + String DOTENV = ''' + FOO=bar + ''' + and: + def result = new MockScriptRunner(['dotenv.relative': '.']) + .setScript(SCRIPT) + .setDotenv(DOTENV, DotenvExtension.DEFAULT_FILENAME, '.') + .execute() + then: + result.val == 'bar' + result.val == Channel.STOP + } + + // TODO: Need a test that tests for default value return from config + // TODO: Need a test for environment variable override +} diff --git a/plugins/nf-dotenv/src/test/nextflow/dotenv/MockHelpers.groovy b/plugins/nf-dotenv/src/test/nextflow/dotenv/MockHelpers.groovy new file mode 100644 index 0000000..3483631 --- /dev/null +++ b/plugins/nf-dotenv/src/test/nextflow/dotenv/MockHelpers.groovy @@ -0,0 +1,235 @@ +/* Copyright 2022, Seqera Labs + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package nextflow.dotenv + +import groovyx.gpars.dataflow.DataflowBroadcast +import nextflow.Session +import nextflow.executor.Executor +import nextflow.executor.ExecutorFactory +import nextflow.processor.TaskHandler +import nextflow.processor.TaskMonitor +import nextflow.processor.TaskRun +import nextflow.processor.TaskStatus +import nextflow.script.ChannelOut +import nextflow.script.ScriptRunner +import nextflow.script.ScriptType + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths + +/** A class for mock running of a Nextflow main script. */ +class MockScriptRunner extends ScriptRunner { + + // TODO: Use faster in-memory testing when upstream supports it: https://github.com/cdimascio/dotenv-java/issues/59 + // /** An in-memory filesystem for unit testing. */ + // static private FileSystem fs = Jimfs.newFileSystem(Configuration.unix()) + // + // static private Path tmpDir = { + // Path tmp = fs.getPath('/tmp') + // tmp.mkdir() + // Path test = Files.createTempDirectory(tmp, 'test') + // test + // }() + + /** Return a random temporary directory for testing. */ + static private Path tmpDir = { + Path tmp = Path.of(System.getProperty('java.io.tmpdir')) + tmp.mkdir() + Path test = Files.createTempDirectory(tmp, 'test') + test + }() + + /** Create a temporary file in the in-memory filesystem for unit tests. + * + * @pararm name The name of the temporary file. + * @param content The content of the temporary file, if any. + * @param relative The relative modifier to the temporary file e.g. 'child-folder/' + */ + static private Path createInMemTempFile(String name, String content=null, String relative=null) { + Path result + if (relative) { + tmpDir.resolve(relative).mkdir() + result = tmpDir.resolve(relative).resolve(name) + } else { + result = tmpDir.resolve(name) + } + if (content) { + result.text = content + } + result + } + + /** Instantiate a new mock script runner from a config dictionary. */ + MockScriptRunner(Map config) { + + super(new MockSession(config)) + } + + /** Set the script `main.nf` with specific contents. */ + MockScriptRunner setScript(String str) { + Path script = createInMemTempFile('main.nf', str) + setScript(script) + return this + } + + /** Set the configuration file `.env` with specific contents. */ + MockScriptRunner setDotenv(String str, String filename=DotenvExtension.DEFAULT_FILENAME, String relative=null) { + createInMemTempFile(filename, str, relative) + return this + + } + + /** Normalize the output of the script result so it is easier to compare. */ + @Override + def normalizeOutput(output) { + if (output instanceof ChannelOut) { + def list = new ArrayList(output.size()) + for (int i=0; i(output.size()) + for (def item : output) { + ((List)result).add(read0(item)) + } + return result + } + + else { + return read0(output) + } + } + + /** Read the dataflow broadcast channel. */ + private static read0(obj) { + if (obj instanceof DataflowBroadcast) { + return obj.createReadChannel() + } + return obj + } + +} + +/** A mock Nextflow session. */ +class MockSession extends Session { + + @Override + Session start() { + this.executorFactory = new MockExecutorFactory() + return super.start() + } + + MockSession(Map config) { + super(config) + } +} + +/** A mock Nextflow executor factory. */ +class MockExecutorFactory extends ExecutorFactory { + + /** The class of executor this factory builds. */ + @Override + protected Class getExecutorClass(String executorName) { + return MockExecutor + } + + /** This is a mock factory so of course we support everything! We're a mock! */ + @Override + protected boolean isTypeSupported(ScriptType type, Object executor) { + true + } +} + +/** A mock Nextflow executor. */ +class MockExecutor extends Executor { + + /** Signal the executor is finished. */ + @Override + void signal() { } + + /** Create a mock task monitor. */ + protected TaskMonitor createTaskMonitor() { + new MockMonitor() + } + + /** Create a mock task handler. */ + @Override + TaskHandler createTaskHandler(TaskRun task) { + return new MockTaskHandler(task) + } +} + +/** A mock Nextflow monitor. */ +class MockMonitor implements TaskMonitor { + + /** Schedule a task handler. */ + void schedule(TaskHandler handler) { + handler.submit() + } + + /** Remove a task handler. */ + boolean evict(TaskHandler handler) { void } + + /** Start this task monitor. */ + TaskMonitor start() { void as TaskMonitor } + + /** Signal the monitor is finished. */ + void signal() { } +} + +/** A mock Nextflow task handler. */ +class MockTaskHandler extends TaskHandler { + + /** Build a mock Nextflow task handler from a task. */ + protected MockTaskHandler(TaskRun task) { + super(task) + } + + /** Submit this task. */ + @Override + void submit() { + log.info ">> launching mock task: ${task}" + if (task.type == ScriptType.SCRIPTLET) { + task.workDir = Paths.get('.').complete() + task.stdout = task.script + task.exitStatus = 0 + } + else { + task.code.call() + } + status = TaskStatus.COMPLETED + task.processor.finalizeTask(task) + } + + /** Check if this task is still running but since we are mock, it's totally finished. */ + @Override + boolean checkIfRunning() { + false + } + + /** Check if this task is completed but since we are mock, it's totally completed. */ + @Override + boolean checkIfCompleted() { + true + } + + /** Kill the thing that never existed, yeah that's right, kill the void. */ + @Override + void kill() { void } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..bd20680 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,7 @@ +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' +} + +rootProject.name = 'nf-dotenv' +include('plugins') +include('plugins:nf-dotenv')