Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Write your shell scripts on the JVM (java, kotlin, groovy, etc.)

NotificationsYou must be signed in to change notification settings

fizzed/blaze

Repository files navigation

Maven Central

Automated Testing

The following Java versions and platforms are tested using GitHub workflows:

Java 8Java 11Java 17Java 21

Linux x64MacOS arm64Windows x64

The following platforms are tested using theFizzed, Inc. build system:

Linux arm64Linux riscv64Linux MUSL x64MacOS x64Windows arm64FreeBSD x64OpenBSD x64

Overview

A speedy, flexible, general purpose scripting and application launching stack forthe JVM. Can replace shell scripts and plays nicely with other tools. Onlyrequires a Java 8 runtime and addingblaze.jar to your project directory. Startwriting portable and cross-platform scripts.

Blaze pulls together stable, mature libraries from the Java ecosystem into alight-weight package that lets you focus on getting things done. When youinvoke blaze, it does the following:

  • Sets up console logging
  • Loads your optional configuration file(s)
  • Downloads runtime dependencies (e.g. jars from Maven central)
  • Loads and compiles your script(s)
  • Executes "tasks" (methods your script defines)

Includes the following features:

  • Write your applications (scripts) in whatever JVM language you prefer.Out-of-the-box support for
    • Java (.java) (8, 11, 17, 21, etc.)
    • Groovy (.groovy) (v4.0.15)
    • Kotlin (.kt) (v1.9.10)
    • JavaScript (.js) (via nashorn on Java 11+)
    • Or write your own (exampleshere,here, andhere)
  • Zero-install required. Just dropblaze.jar into your project directory andyou or others can run it withjava -jar blaze.jar.
  • IDE support
  • Small size so you can commitblaze.jar to your repository
  • Excellent framework support for executing processes, modifying the filesystem,user interaction, http, and ssh.
  • Easily use any Java library as a dependency to accomplish whateverthe framework doesn't provide.

Sponsorship & Support

Project byFizzed, Inc. (Follow on Twitter:@fizzed_inc)

Developing and maintaining opensource projects requires significant time. If you find this project useful or needcommercial support, we'd love to chat. Drop us an email atping@fizzed.com

Project sponsors may include the following benefits:

  • Priority support (outside of Github)
  • Feature development & roadmap
  • Priority bug fixes
  • Privately hosted continuous integration tests for their unique edge or use cases

What is a blaze script?

A Blaze script is a 100% valid JVM class with public methods that typically usesan empty (root) package declaration. Each public method becomes the externallyaccessible task that can be called from the command-line. Since most JVM languagessupport this kind of structure, Blaze can easily support a wide variety ofJVM languages.

More documentation

Try It

To give this project a quick try on your own machine, just run some of the examples:

git clone https://github.com/fizzed/blaze.gitcd blazejava -jar blaze.jar examples/hello.javajava -jar blaze.jar examples/natives.javajava -jar blaze.jar examples/find_javas.java

Install to your project

Downloadblaze.jar to your project directory. If you havewget available

wget -O blaze.jar 'https://repo1.maven.org/maven2/com/fizzed/blaze-lite/1.9.0/blaze-lite-1.9.0.jar'

If you havecurl available

curl -o blaze.jar 'https://repo1.maven.org/maven2/com/fizzed/blaze-lite/1.9.0/blaze-lite-1.9.0.jar'

Or simplydownload the file in your web browserand save it to your project directory with a name ofblaze.jar

Write hello world blaze script in .java

Createblaze.java file

publicclassblaze {publicvoidmain() {System.out.println("Hello World!");    }    }

Run blaze script

Since you named your fileblaze.java, Blaze will find it automatically. Youcan run it like so

java -jar blaze.jar

If no task is supplied on the command line, Blaze will attempt to run themaintask by default.

Write script that executes a process

Let's do a more useful example of how we use Blaze in many cases. Let's sayyou had a Maven project and wanted to execute a class with a main method. Thesyntax to do that in Maven becomes difficult to remember and communicate toother developers. Blaze lets you simplify the entry points to your projectby exposing everything as named tasks.

importstaticcom.fizzed.blaze.Systems.exec;publicclassblaze {publicvoiddemo1() {exec("mvn","compile","exec:java","-Dexec.classpathScope=runtime","-Dexec.mainClass=com.example.Demo1").run();    }publicvoiddemo2() {exec("mvn","compile","exec:java","-Dexec.classpathScope=runtime","-Dexec.mainClass=com.example.Demo2").run();    }}

You can now just run these withjava -jar blaze.jar demo1 orjava -jar blaze.jar demo2

Avoid "Terminate batch job (Y/N)" on CTRL+C in Windows

If you leverage powershell on Windows, Blaze v1.6.0+ will install ablaze.ps1 via the "-i" installer flag. Thispowershell script will help you avoid the infuriating "Terminate batch job (Y/N)" prompt on Windows.

Avoid zombie processes triggered with maven and CTRL+C on Windows

On windows if you run maven, and it in turn creates child processes for javadocs, exec plugin, etc., in almost allcases, maven will close but leave the processes it opened still running. The problem is that Windows itself does notclose the process hierarchy if the parent is terminated, like Linux or MacOS will do.

As of Blaze v1.6.0+, any blaze exec() action will automatically destroy any running processes as well as any childprocesses upon shutdown via CTRL+C (or any reason for an exit). Blaze makes Maven on Windows much easier to use.

But I can still do your previous example in a shell script?

Yeah, I suppose so. But you'd probably use two shell scripts to define theseparate tasks and if you cared about platform portability, you'd be nice toalso include.bat scripts for Windows users. However, when you want to doanything else that's remotely advanced, you'll start to appreciate having amore advanced environment.

An example of finding a specific JDK on your local system to execute a Maven test with it.

find_java.conf

blaze.dependencies = ["com.fizzed:jne:4.1.1"]

find_java.java

publicclassblaze {privatefinalLoggerlog =Contexts.logger();privatefinalConfigconfig =Contexts.config();privatefinalPathprojectDir =withBaseDir("..").toAbsolutePath();@Taskpublicvoidtest()throwsException {// optional command-line arguments to control which jdk version or hardware architecturefinalIntegerjdkVersion =this.config.value("jdk.version",Integer.class).orNull();finalHardwareArchitecturejdkArch =ofNullable(this.config.value("jdk.arch").orNull())              .map(HardwareArchitecture::resolve)              .orElse(null);finallongstart =System.currentTimeMillis();finalJavaHomejdkHome =newJavaHomeFinder()              .jdk()              .version(jdkVersion)              .hardwareArchitecture(jdkArch)              .preferredDistributions()              .sorted(jdkVersion !=null ||jdkArch !=null)// sort if any criteria provided              .find();log.info("");log.info("Detected {} (in {} ms)",jdkHome, (System.currentTimeMillis()-start));log.info("");exec("mvn","clean","test")              .workingDir(projectDir)              .env("JAVA_HOME",jdkHome.getDirectory().toString())              .verbose()              .run();   }    }

Another example where we query git for the latest tag and use it to update a README file with it. We use this as a wayto maintain a README file with the latest version pushed to Maven central

importcom.fizzed.blaze.Contexts;importstaticcom.fizzed.blaze.Contexts.withBaseDir;importstaticcom.fizzed.blaze.Contexts.fail;importstaticcom.fizzed.blaze.Systems.exec;importcom.fizzed.blaze.core.Actions;importcom.fizzed.blaze.core.Blaze;importcom.fizzed.blaze.util.Streamables;importjava.io.BufferedWriter;importjava.io.IOException;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.StandardCopyOption;importjava.util.regex.Matcher;importjava.util.regex.Pattern;importorg.slf4j.Logger;publicclassblaze {staticprivatefinalLoggerlog =Contexts.logger();privateStringlatest_tag() {// get latest tag from gitreturnexec("git","describe","--abbrev=0","--tags")            .runCaptureOutput()            .toString()            .trim();    }publicvoidupdate_readme()throwsIOException {PathreadmeFile =withBaseDir("../README.md");PathnewReadmeFile =withBaseDir("../README.md.new");// find latest version via git tag, trim off leading 'v'StringtaggedVersion =latest_tag().substring(1);log.info("Tagged version: {}",taggedVersion);// find current version in readme using a regex to match// then apply a mapping function to return the first group of each match// then we only need to get the first matched groupStringversionRegex =".*lite-(\\d+\\.\\d+\\.\\d+)\\.jar.*";StringreadmeVersion            =Streamables.matchedLines(input(readmeFile),versionRegex, (m) ->m.group(1))                .findFirst()                .get();log.info("Readme version: {}",readmeVersion);if (readmeVersion.equals(taggedVersion)) {log.info("Versions match (no need to update README)");return;        }// replace version in file and write a new versionfinalPatternreplacePattern =Pattern.compile(readmeVersion);try (BufferedWriterwriter =Files.newBufferedWriter(newReadmeFile)) {Files.lines(readmeFile)                .forEach((l) -> {Matchermatcher =replacePattern.matcher(l);StringnewLine =matcher.replaceAll(taggedVersion);try {writer.append(newLine);writer.append("\n");                    }catch (IOExceptione) {thrownewUncheckedIOException(e);                    }                });writer.flush();        }// replace readme with updated versionFiles.move(newReadmeFile,readmeFile,StandardCopyOption.REPLACE_EXISTING);    }}

Optionally install blaze on your PATH

While you can invokeblaze.jar as an executable jar by running

java -jar blaze.jar

Sometimes it's more convenient to have a system-wide executable installed onyour PATH to make that even shorter. Blaze has a built-in method to copy awrapper script to a directory. On Linux or Mac OSX, you can run the following

sudo java -jar blaze.jar -i /usr/local/bin

On Windows, open up a shell as an administrator (Start Menu -> Command Prompt >right mouse click Run as administrator), then run the following

java -jar blaze.jar -i C:\Windows\System32

Depending on your operating system, this will install either ablaze shellscript or ablaze.bat batch script. Assuming/usr/local/bin orC:\Windows\System32is already on your PATH (which normally it is), then you can now just runthe following in your shell

blaze

IDE support

Writing your blaze scripts in an IDE is significantly more productive than trying to write them in a text editor. Weinitially tried writing our own IDE plugins to automatically recognize blaze was present, but that proved too difficultto maintain over IDE versions. As of Blaze v1.9.0+, there is a new simple method to enable IDE support across anyIDE that supports Maven projects.

java -jar blaze.jar --generate-maven-project

This command will leverage the location of the script currently being executed, calculate the dependencies it needs torun, and then create a minimal pom.xml in the same directory. You can then open that pom.xml in any IDE, and you'll getall the full blown features of your IDE to efficiently write and maintain your blaze scripts.

The--generate-maven-project command will set the target source version to Java 8 by default. If you need to overridethis to something else, you can add a [blaze-script].conf file that is associated with your blaze script, and add thefollowing configuration values:

java.source.version = 11

You can also pass this is on the command line:

blaze --generate-maven-project -Djava.source.version=17

Where to save your script(s)

Blaze is designed to play nicely with other popular JVM build tools such as Maven,Gradle, Ant, SBT, etc. Blaze is also designed to play nicely with your favoriteIDE. If you are planning on a blaze-only project, then create ablaze.[ext]file in your project directory (at the same level as yourblaze.jar). Yourproject directory would be

<project directory>/    blaze.jar    blaze.[ext]

The[ext] would be whatever JVM language you'd like to write your script in.So java would be.java, groovy would be.groovy, etc.

However, if you are using another build tool such as Maven, we'd suggest creatinga sub-directory called.blaze orblaze and placing yourblaze.[ext] script in there.Most Java IDEs compute classpaths for auto completion based on directory pathsand placing your script in the root directory doesn't work very well with IDEs likeNetbeans. So a maven project + blaze would be

<project directory>/    .blaze/        blaze.[ext]    blaze.jar    pom.xml

In either setup, you'd run your script identically. That's because blaze willfirst search the current directory forblaze.[ext] then.blaze/blaze.[ext]thenblaze/blaze.[ext]

If you'd like to have more than one script, you can supply it on the command-linelike so

java -jar blaze.jar path/to/script.[ext]

Usage for developing blaze extensions

<dependencies>  <dependency>    <groupId>com.fizzed</groupId>    <artifactId>blaze-core</artifactId>    <version>1.9.0</version>    <scope>provided</scope>  </dependency></dependencies>

[8]ページ先頭

©2009-2025 Movatter.jp