diff --git a/Cargo.lock b/Cargo.lock index a362a14..c7b901d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -709,7 +709,7 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "swim-create" -version = "0.2.0" +version = "0.4.0" dependencies = [ "clap", "regex", diff --git a/Cargo.toml b/Cargo.toml index 529941c..2d22eaf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "swim-create" -version = "0.3.0" +version = "0.4.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/main.rs b/src/main.rs index 57f37f3..20db62e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,14 +2,12 @@ mod error; mod utils; use crate::utils::*; -use clap::Parser; +use clap::{Parser, ValueEnum}; use rust_embed::RustEmbed; use serde::Serialize; use std::fmt::Debug; use std::path::Path; -const PROJECT_TEMPLATE_FOLDER: &str = "swim-template"; - #[derive(Parser, Debug, Serialize)] #[command(author, version, about, long_about = None)] struct Args { @@ -21,14 +19,35 @@ struct Args { #[arg(short, long, default_value_t = 9001)] port: u16, /// The version of the Swim server dependencies. - #[arg(short, long, default_value = "4.1.0.12")] + #[arg(short, long, default_value = "4.2.14")] swim_version: String, + /// The type of the project template. + #[arg(short, long, value_enum, default_value_t = Template::Gradle)] + template_type: Template, +} + +#[derive(ValueEnum, Clone, Default, Debug, Serialize)] +#[serde(rename_all = "kebab-case")] +enum Template { + /// Java template using Gradle. + #[default] + Gradle, + /// Java template with a module using Gradle. + GradleModule, +} + +impl Template { + pub fn get_folder(&self) -> String { + match self { + Template::Gradle => "swim-gradle-template".to_string(), + Template::GradleModule => "swim-gradle-module-template".to_string(), + } + } } #[derive(RustEmbed)] #[folder = "templates"] -#[exclude = "swim-template/.git/*"] -struct Templates; +struct TemplatesDir; fn main() { let args = Args::parse(); @@ -38,7 +57,9 @@ fn main() { std::process::exit(1) } - for path in Templates::iter() { + let template_folder = args.template_type.get_folder(); + + for path in TemplatesDir::iter().filter(|path| path.starts_with(&template_folder)) { if let Err(err) = create_file(Path::new(&path.to_string()), &args) { println!("{}", err); std::process::exit(1) diff --git a/src/utils.rs b/src/utils.rs index b9c1edd..bf2c79a 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,5 +1,5 @@ use crate::error::CliError; -use crate::{Args, Templates, PROJECT_TEMPLATE_FOLDER}; +use crate::{Args, TemplatesDir}; use regex::Regex; use serde::Serialize; use std::error::Error; @@ -63,7 +63,7 @@ pub(crate) fn create_regular_file( output_file: &String, args: &Args, ) -> Result<(), CliError> { - let input_file = Templates::get(&input_file.display().to_string()) + let input_file = TemplatesDir::get(&input_file.display().to_string()) .ok_or(CliError::missing_file_err(output_file.clone()))?; let input_text = String::from_utf8(input_file.data.to_vec()) @@ -79,7 +79,7 @@ pub(crate) fn create_regular_file( } pub(crate) fn create_jar_file(input_file: &Path, output_file: &String) -> Result<(), CliError> { - let input_file = Templates::get(&input_file.display().to_string()) + let input_file = TemplatesDir::get(&input_file.display().to_string()) .ok_or(CliError::missing_file_err(output_file.clone()))?; fs::write(output_file, input_file.data) @@ -100,7 +100,8 @@ pub(crate) fn set_executable_permissions(output_file: &String) -> Result<(), Cli } pub(crate) fn get_output_dir(input_dir: &Path, args: &Args) -> Result> { - let output_dir = Path::new(&args.name).join(input_dir.strip_prefix(PROJECT_TEMPLATE_FOLDER)?); + let output_dir = + Path::new(&args.name).join(input_dir.strip_prefix(args.template_type.get_folder())?); replace_text(&output_dir.display().to_string(), args) } diff --git a/templates/swim-template/.gitignore b/templates/swim-gradle-module-template/.gitignore similarity index 100% rename from templates/swim-template/.gitignore rename to templates/swim-gradle-module-template/.gitignore diff --git a/templates/swim-template/build.gradle b/templates/swim-gradle-module-template/build.gradle similarity index 100% rename from templates/swim-template/build.gradle rename to templates/swim-gradle-module-template/build.gradle diff --git a/templates/swim-template/gradle/wrapper/gradle-wrapper.jar b/templates/swim-gradle-module-template/gradle/wrapper/gradle-wrapper.jar similarity index 100% rename from templates/swim-template/gradle/wrapper/gradle-wrapper.jar rename to templates/swim-gradle-module-template/gradle/wrapper/gradle-wrapper.jar diff --git a/templates/swim-template/gradle/wrapper/gradle-wrapper.properties b/templates/swim-gradle-module-template/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from templates/swim-template/gradle/wrapper/gradle-wrapper.properties rename to templates/swim-gradle-module-template/gradle/wrapper/gradle-wrapper.properties diff --git a/templates/swim-template/gradlew b/templates/swim-gradle-module-template/gradlew similarity index 100% rename from templates/swim-template/gradlew rename to templates/swim-gradle-module-template/gradlew diff --git a/templates/swim-template/gradlew.bat b/templates/swim-gradle-module-template/gradlew.bat similarity index 100% rename from templates/swim-template/gradlew.bat rename to templates/swim-gradle-module-template/gradlew.bat diff --git a/templates/swim-template/settings.gradle b/templates/swim-gradle-module-template/settings.gradle similarity index 100% rename from templates/swim-template/settings.gradle rename to templates/swim-gradle-module-template/settings.gradle diff --git a/templates/swim-template/src/main/java/module-info.java b/templates/swim-gradle-module-template/src/main/java/module-info.java similarity index 100% rename from templates/swim-template/src/main/java/module-info.java rename to templates/swim-gradle-module-template/src/main/java/module-info.java diff --git a/templates/swim-template/src/main/java/{{name}}/MainPlane.java b/templates/swim-gradle-module-template/src/main/java/{{name}}/MainPlane.java similarity index 100% rename from templates/swim-template/src/main/java/{{name}}/MainPlane.java rename to templates/swim-gradle-module-template/src/main/java/{{name}}/MainPlane.java diff --git a/templates/swim-template/src/main/resources/server.recon b/templates/swim-gradle-module-template/src/main/resources/server.recon similarity index 100% rename from templates/swim-template/src/main/resources/server.recon rename to templates/swim-gradle-module-template/src/main/resources/server.recon diff --git a/templates/swim-gradle-template/.gitignore b/templates/swim-gradle-template/.gitignore new file mode 100644 index 0000000..1f94fa7 --- /dev/null +++ b/templates/swim-gradle-template/.gitignore @@ -0,0 +1,3 @@ +.idea +.gradle +build diff --git a/templates/swim-gradle-template/build.gradle b/templates/swim-gradle-template/build.gradle new file mode 100644 index 0000000..3add4cb --- /dev/null +++ b/templates/swim-gradle-template/build.gradle @@ -0,0 +1,13 @@ +apply plugin: 'application' + +version = '0.0.1' +mainClassName = '{{name}}.MainPlane' +ext.moduleName = '{{name}}' + +repositories { + mavenCentral() +} + +dependencies { + implementation group: 'org.swimos', name: 'swim-server', version: '{{swim_version}}' +} \ No newline at end of file diff --git a/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.jar b/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.jar differ diff --git a/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.properties b/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..62f495d --- /dev/null +++ b/templates/swim-gradle-template/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/templates/swim-gradle-template/gradlew b/templates/swim-gradle-template/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/templates/swim-gradle-template/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/templates/swim-gradle-template/gradlew.bat b/templates/swim-gradle-template/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/templates/swim-gradle-template/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/templates/swim-gradle-template/settings.gradle b/templates/swim-gradle-template/settings.gradle new file mode 100644 index 0000000..c153cb2 --- /dev/null +++ b/templates/swim-gradle-template/settings.gradle @@ -0,0 +1 @@ +rootProject.name="{{name}}" diff --git a/templates/swim-gradle-template/src/main/java/{{name}}/MainPlane.java b/templates/swim-gradle-template/src/main/java/{{name}}/MainPlane.java new file mode 100644 index 0000000..4774ede --- /dev/null +++ b/templates/swim-gradle-template/src/main/java/{{name}}/MainPlane.java @@ -0,0 +1,16 @@ +package {{name}}; + +import swim.api.plane.AbstractPlane; +import swim.kernel.Kernel; +import swim.server.ServerLoader; + +public class MainPlane extends AbstractPlane { + + public static void main(String[] args) { + final Kernel kernel = ServerLoader.loadServer(); + System.out.println("Starting server..."); + kernel.start(); + System.out.println("Running server..."); + kernel.run(); + } +} diff --git a/templates/swim-gradle-template/src/main/resources/server.recon b/templates/swim-gradle-template/src/main/resources/server.recon new file mode 100644 index 0000000..3c03e43 --- /dev/null +++ b/templates/swim-gradle-template/src/main/resources/server.recon @@ -0,0 +1,6 @@ +{{name}}: @fabric { + @plane(class: "{{name}}.MainPlane") +} +@web(port: {{port}}) { + space: "{{name}}" +} \ No newline at end of file