Giter Site home page Giter Site logo

jbangdev / jbang Goto Github PK

View Code? Open in Web Editor NEW
1.4K 24.0 151.0 5.54 MB

Unleash the power of Java - JBang Lets Students, Educators and Professional Developers create, edit and run self-contained source-only Java programs with unprecedented ease.

Home Page: https://jbang.dev

License: MIT License

Java 93.67% Shell 3.20% Batchfile 0.36% PowerShell 0.82% Gherkin 1.53% JavaScript 0.14% Smarty 0.23% Groovy 0.01% Kotlin 0.03%
scripting bash java shell hacktoberfest

jbang's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jbang's Issues

Configuring multi-value defaults in list option in tz example

Hi Max, congrats again on jbang, nice work!

The tz example mentions some difficulty with configuring defaults for multi-value options.

It is possible in picocli to configure default values for a multi-value option, if you are willing to allow comma-separated values. You would do that by setting the split = "," attribute in the @Option or @Parameters annotation. Then you can set multiple default values in a single string:

@Parameters(split = ",", defaultValue = "1,2,3") List<Integer> myNumbers;

Similarly for tz:

class ListDefaults {
    @Parameters(split = ",",
            defaultValue = "America/Los_Angeles,America/Detroit,Europe/London,Europe/Zurich,Asia/Kolkata,Australia/Brisbane",
            description = "Time zones. Defaults: ${DEFAULT-VALUE}.",
            hideParamSyntax = true, paramLabel = "[<zones>[,<zones>...]...]")
    List<ZoneId> zones;

    public static void main(String[] args) {
        ListDefaults instance = CommandLine.populateCommand(new ListDefaults()); // without args
        System.out.println("ZoneIds are: " + instance.zones);

        System.out.println();
        System.out.println("It makes the parameter label in the usage help a bit verbose though...");
        System.out.println("So we set a custom label.");
        System.out.println();
        new CommandLine(new ListDefaults())
                .setUsageHelpLongOptionsMaxWidth(30) // requires picocli 4.2
                .usage(System.out);
    }
}

enable gradle run

by adding application plugin plus specifiying main class you can do gradle run.

plugins {
    id 'java'
    id 'application'
}

repositories {
    mavenLocal()
        jcenter()
}

dependencies {
        
}


application {
    mainClassName = 'piping'
}

Support passing VM properties with `-Dx=y`

From #51: I tried switching on picocli's built-in debug tracing. I ended up changing the source code of the tz main method to do this, because I could not figure out how to pass -Dpicocli.trace=DEBUG on the command line. I tried these:

remko@LAPTOP-7EO0MTL0:/mnt/c/Users/remko/IdeaProjects/jbang$ jbang -Dpicocli.trace=DEBUG examples/tz.java 15:00
Unknown option: '-Dpicocli.trace=DEBUG'
Usage: jbang [-eh] [--verbose] [--version] [--clear-cache] [--completion]
...

and

remko@LAPTOP-7EO0MTL0:/mnt/c/Users/remko/IdeaProjects/jbang$ jbang examples/tz.java -Dpicocli.trace=DEBUG 15:00
Unknown option: '-Dpicocli.trace=DEBUG'

In both cases, picocli is parsing the option and treats it as an application option: first of the jbang application, and next of the tz application. It may be worth treating -Dx=y options to jbang as special and pass them as VM parameters.


Note that options between the jbang command and the script name should be treated as VM args:

jbang -Dx=y script [options]

While options after the script name should be treated as arguments for the script, just like any other option (not a VM parameter):

jbang script  -Dx=y

Fails to run jbang --edit

I can run a chmod+x'ed Hello.java file from a terminal, but when trying to generate a build file to open it in my IDE, it fails with an exception:

➜  jbang java -version
openjdk version "13" 2019-09-17
OpenJDK Runtime Environment Zulu13.27+9-CA (build 13+33)
OpenJDK 64-Bit Server VM Zulu13.27+9-CA (build 13+33, mixed mode, sharing)
➜  jbang ./Hello.java             
0 [main] INFO Hello  - Welcome to jbang
2 [main] INFO Hello  - Hello from Java!
➜  jbang jbang --edit Hello.java
dk.xam.jbang.ExitException
        at dk.xam.jbang.Main.quit(Main.java:75)
        at dk.xam.jbang.Main.call(Main.java:119)
        at dk.xam.jbang.Main.call(Main.java:27)
        at picocli.CommandLine.executeUserObject(CommandLine.java:1783)
        at picocli.CommandLine.access$900(CommandLine.java:145)
        at picocli.CommandLine$RunLast.handle(CommandLine.java:2141)
        at picocli.CommandLine$RunLast.handle(CommandLine.java:2108)
        at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975)
        at picocli.CommandLine.execute(CommandLine.java:1904)
        at dk.xam.jbang.Main.main(Main.java:79)
/Users/fbricon/.jbang/temp_projects/jbang_tmp_project__Hello.java_8726bd513b68378f53ba944e3c15ddb0966e9e41eabbf79e6b58270055699479

The source file, Hello.java :

//usr/bin/env jbang "$0" "$@" ; exit $?

//DEPS log4j:log4j:1.2.17 

import static java.lang.System.out;

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

import java.util.Arrays;

class Hello {

	static final Logger logger = Logger.getLogger(Hello.class);

	public static void main(String[] args) {
		BasicConfigurator.configure(); 
		logger.info("Welcome to jbang");

		Arrays.asList(args).forEach(arg -> logger.warn("arg: " + arg));
		logger.info("Hello from Java!");
	}
}

support for adding a BOM pom as dependency

would be cool to be able to use a BOM pom to define the versions for related dependencies so you don't need to provide specific versions

//DEPS com.azure:azure-sdk-bom:1.0.0-beta.1 com.azure:azure-identity com.azure:azure-security-keyvault-secrets

maybe prefix it with something pom: or it should be possible to determine it from the type

HTTP 301 not supported

Getting the following exception when a server returns a 301 Moved Permanently:

[jbang] Could not download http://gitlab.cee.redhat.com/blah/blah/blah/Foo.java
dk.xam.jbang.ExitException: Could not download http://gitlab.cee.redhat.com/blah/blah/blah/Foo.java
	at dk.xam.jbang.Main.fetchFromURL(Main.java:830)
	at dk.xam.jbang.Main.prepareScript(Main.java:757)
	at dk.xam.jbang.Main.doCall(Main.java:236)
	at dk.xam.jbang.Main.call(Main.java:254)
	at dk.xam.jbang.Main.call(Main.java:35)
	at picocli.CommandLine.executeUserObject(CommandLine.java:1783)
	at picocli.CommandLine.access$900(CommandLine.java:145)
	at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2150)
	at picocli.CommandLine$RunLast.handle(CommandLine.java:2144)
	at picocli.CommandLine$RunLast.handle(CommandLine.java:2108)
	at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:1975)
	at picocli.CommandLine.execute(CommandLine.java:1904)
	at dk.xam.jbang.Main.main(Main.java:121)
Caused by: java.io.FileNotFoundException: No file to download. Server replied HTTP code: 301
	at dk.xam.jbang.Util.downloadFile(Util.java:105)
	at dk.xam.jbang.Main.fetchFromURL(Main.java:826)
	... 12 more

(Sanitized URL because it's from the corporate network. Ask me in private if you need it to reproduce)

allow for additional source files

in some cases libraries just need full public classes and with default jbang you can only have one.

would be interesting to allow for something like:

//FRIENDS Person.java Order.java

that would add these to the java compile source files list. This would also be possible to work with url based by simply fetching them relative to url location.

could even allow for

//FRIENDS *.java

but that would NOT work in the url case so i'm hesitant to include eit.

run Maven artifacts directly

Explore the possibility to do something like jbang org.groupid:artifactid or jbang org.groupid:artifactid org.groupid.artifactid.MyMainClass where the first argument would be the name of a Maven artifact to run.

The first form would be for a Maven artifact that has a Main-Class set in their MANIFEST, the second form would be for those that haven't.

@maxandersen suggested to use the form jbang mvn://org.groupid:artifactid which would work too (although we could/should perhaps drop the 2 slashes)

[idea] make imports section optional

The idea is to make the user focus on coding and omit necessarily of thinking about imports.
The idea is to reduce the time that is needed to Google something-> Find it on StackOverflow-> paste it in editor -> run it

The way how do I see the possible implementation is to scan the entire classpath, grab all possible classes, add them all to imports, let the compiler decide what is needed and what can be removed in the real class.

WDYT?

warn users if javac version is higher than java

some users might have a setup where java is of a lower version than javac meaning they will get a classfile major version error.

We could run java -version / javac -version and just check that java numbers are same or bigger than javac

jbang --init=<template>

would be nice to have templates for jbang init ...
i.e.

jbang --init=cli mycli

would give you something like:

//usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.1.4

import picocli.CommandLine;

import java.text.MessageFormat;
import java.util.concurrent.Callable;

import static java.lang.System.*;

@CommandLine.Command(name = "mycli", mixinStandardHelpOptions = true, version = "0.1",
        description = "mycli made by jbang")
public class mycli implements Callable<Integer> {

    public static void main(String... args) {
        int exitCode = new CommandLine(new analytics()).execute(args);
        System.exit(exitCode);
    }

    @Override
    public Integer call() throws Exception {
        System.out.println("Hello World!");
        return 0;
    }
}

jbang should display a proper error message when older jdk version are used.

I am currently getting this error message when using jbang with jdk8.

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: 
dk/xam/jbang/Main has been compiled by a more recent version of the Java Runtime 
(class file version 55.0), this version of the Java Runtime only recognizes class file 
versions up to 52.0
	at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

The jbang script should detect that and display a proper error message.

enable launch of javafx

JavaFX is tricky or maybe its just very picky ;)

jbang https://raw.githubusercontent.com/maxandersen/jbang/master/examples/jfxarc.java

Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: jfxarc
	at javafx.application.Application.launch(Application.java:304)
	at jfxarc.main(jfxarc.java:43)
Caused by: java.lang.ClassNotFoundException: jfxarc
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)

Need to see if in the special case of jfx if we can do some transformation in jbang to make it happy at launch time.

generate .launch to aid eclipse and launch.json for vscode

could create a .launch in root of project to get easy launch using same arguments as passed in.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
    <booleanAttribute key="org.eclipse.jdt.launching.ATTR_EXCLUDE_TEST_CODE" value="true"/>
    <booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_CLASSPATH_ONLY_JAR" value="false"/>
    <booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_START_ON_FIRST_THREAD" value="true"/>
    <stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="piping"/>
    <stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="wonka bonka"/>
    <stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="jbang_tmp_project__piping.java_f13ecd69de78cd5a076093583ce9c0c708badeceeec80d72adfc593e267f47f8"/>
</launchConfiguration>

Add jbang —init

Really cool project and I can see myself using it on a daily basis.
Would be nice to have some sort of init operation to scaffold the main method, shebang and sample deps for reference (like import logback or some other logger).
There’s a few moving pieces to look up each time you’d create a script.

Failed to resolve OS dependant maven artifacts

With version 0.13.2. Was working with 0.8.1:

jbang docker_java.java
[jbang] Resolving dependencies...
[jbang]     Resolving com.github.docker-java:docker-java:3.1.5...Feb 03, 2020 3:18:58 PM org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener transferFailed
WARNING: Failed downloading io/netty/netty-transport-native-unix-common/4.1.31.Final/netty-transport-native-unix-common-4.1.31.Final-$%7Bos.detected.name%7D-$%7Bos.detected.arch%7D.jar from https://jcenter.bintray.com/. Reason:
org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact io.netty:netty-transport-native-unix-common:jar:${os.detected.name}-${os.detected.arch}:4.1.31.Final in jcenter (https://jcenter.bintray.com/)
Feb 03, 2020 3:18:59 PM org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener transferFailed
WARNING: Failed downloading io/netty/netty-tcnative/2.0.19.Final/netty-tcnative-2.0.19.Final-$%7Bos.detected.classifier%7D.jar from https://jcenter.bintray.com/. Reason:
org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact io.netty:netty-tcnative:jar:${os.detected.classifier}:2.0.19.Final in jcenter (https://jcenter.bintray.com/)
Feb 03, 2020 3:18:59 PM org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener transferFailed
WARNING: Failed downloading io/netty/netty-tcnative/2.0.19.Final/netty-tcnative-2.0.19.Final-$%7Bos.detected.classifier%7D.jar from https://repo.maven.apache.org/maven2/. Reason:
org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact io.netty:netty-tcnative:jar:${os.detected.classifier}:2.0.19.Final in central (https://repo.maven.apache.org/maven2)
Feb 03, 2020 3:18:59 PM org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener transferFailed
WARNING: Failed downloading io/netty/netty-transport-native-unix-common/4.1.31.Final/netty-transport-native-unix-common-4.1.31.Final-$%7Bos.detected.name%7D-$%7Bos.detected.arch%7D.jar from https://repo.maven.apache.org/maven2/. Reason:
org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact io.netty:netty-transport-native-unix-common:jar:${os.detected.name}-${os.detected.arch}:4.1.31.Final in central (https://repo.maven.apache.org/maven2)

Reproducer is here.

enable/document repl.it usecase

repl.it allows for easy java scripting environments.

you can run:

curl -Ls "https://github.com/maxandersen/jbang/releases/download/v0.5.0/jbang-0.5.0.zip" --output jbang.zip \
              && jar xf jbang.zip && mv jbang-* jbang && chmod +x jbang/bin/jbang

and then

.repl.it have
run = "jbang/bin/jbang yourfile.java"

and it will work.

ideas:

  • have a bootstrap that will fallback to that install mechanism if sdkman is not available so ./myfile.java will work.
  • see if repl.it allow setting up pre-actions to download
  • get repl.it to add jbang to its default install (see https://repl.it/feedback/p/jbang-available-in-java-repl)

add --edit-live for live editing

add --edit-live option that in pseudo does something like:

{$JBANG_EDITOR:$EDITOR} jbang --edit xyz.java
file watch xyz.java and on every change, check if deps changed and can be resolved regenerate project
so dependencies will be kept up to date.

support Java 8+

currently we run the file directly using 'java filename', this gives the benefit that filename != classname.

but to support java8+ (and possibly also javafx launch #19 ) then a compile step is needed.

Have the advantage of being able to cache the build results too for faster startup.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.