JBang Documentation

repository·main·Indexed 23 days ago

https://github.com/jbangdev/jbang

A tool for running Java applications and scripts without local installations. JBang supports executing code from Markdown files, managing JDKs, handling dependencies via //DEPS directives, and providing a comprehensive CLI for application lifecycle, exporting, and alias management.

Tokens
80K
Snippets
217
Records
465
Agent score
83%

What's inside JBang

  1. Overview of JBang features and capabilities

    main

    JBang is a tool designed to make Java scripting easy by removing traditional project setup overhead. It allows you to run Java files directly, manage dependencies via //DEPS declarations, and support multiple languages including .java, .jsh, .kt, .groovy, and .md.

    Key capabilities include:

    • Dependency Management: Automatic resolution of libraries.
    • Native Images: Generation of native binaries using GraalVM.
    • IDE Integration: Full editor support via jbang edit.
    • Templates: Rapid scaffolding of new scripts.
    • Aliases & Catalogs: Easy sharing and reuse of scripts.
    • Cross-Platform: Support for Windows, macOS, Linux, and AIX.
  2. Overview of JBang CLI commands

    main

    JBang provides a comprehensive CLI for managing Java applications, dependencies, JDKs, and configurations. The primary command groups include:

    • Execution & Lifecycle: run, build, init, edit.
    • Dependency Management: deps (with search and add subcommands).
    • Caching: cache (with clear subcommand).
    • Exporting: export (supports portable, local, mavenrepo, native, fatjar, jlink, gradle, and maven formats).
    • JDK Management: jdk (with install, list, uninstall, home, env, exec, and default subcommands).
    • Configuration: config (with get, set, unset, and list subcommands).
    • Security: trust (to manage trusted sources/scripts).
    • Aliases & Templates: alias and template for managing shortcuts and project scaffolds.
    • Catalogs: catalog for managing external dependency catalogs.
    • Application Management: app (to install, list, uninstall, or setup JBang applications).
    • Information & System: info (for tools, classpath, jar, and docs), version, completion (shell completion), and wrapper (to install JBang wrappers).
  3. Use implicit alias catalogs

    main

    JBang supports "implicit catalogs," allowing you to run aliases from remote sources using a special <alias>@<provider> syntax. JBang automatically resolves the location based on the provider.

    Syntax Patterns

    • <alias>@<hostname>(/path/to/catalog): Resolves to a catalog at a specific URL.
    • <alias>@<user/org>(/repository)(/branch)(~path): Resolves to a Git-backed service (GitHub, GitLab, or Bitbucket).

    Examples

    |== | Command | Description | jbang hello@acme.corp | Looks for https://acme.corp/jbang-catalog.json or searches GitHub/GitLab/Bitbucket. | jbang hello@acme.corp/a/path/to/jbang-catalog.json | Looks for the catalog at the specific path on acme.corp. | jbang hello@acme | Looks for acme/jbang-catalog/jbang-catalog.json on GitHub, GitLab, or Bitbucket. | jbang hello@acme/mycatalog | Looks for acme/mycatalog/jbang-catalog.json on GitHub, GitLab, or Bitbucket. | jbang hello@acme/mycatalog/dev | Looks for the catalog in the dev branch. | jbang hello@acme~experimental | Looks for acme/jbang-catalog/experimental/jbang-catalog.json. |==

    Note: If a name contains a dot (e.g., jbang tree@jbang.dev), JBang first looks for a catalog at https://jbang.dev/jbang-catalog.json.

  4. Parameterize dependencies with properties

    main

    You can use environment variables and system properties in your //DEPS declarations using the format ${[env.]propertyname:<defaultvalue>}.

    JBang provides properties similar to os-maven-plugin (e.g., ${os.name}) and a specific property for JavaFX (${os.detected.jfxname}) to help make scripts portable across operating systems.

    Example of using an OS-detected property:

    //DEPS org.openjfx:javafx-graphics:11.0.2:${os.detected.jfxname}
  5. Use the Interactive REPL with jshell

    main

    Using jbang --interactive enables a REPL environment powered by jshell. This allows you to explore your script and its dependencies interactively.

    When running Java/JAR scripts in interactive mode, JBang provides a userMain function. This function delegates to the script's main function. You can invoke it with arguments using userMain(args).

    Note: jshell cannot access classes in the default package. You must add a package statement to your script/class to make it visible in the REPL.

  6. Declare dependencies in single-file Java programs

    main

    For single-file programs, you can declare dependencies using //DEPS comments instead of a traditional build file (like pom.xml). JBang will resolve these from Maven Central or other configured repositories and add them to the classpath.

    Example: CLI app with Picocli dependency

    ///usr/bin/env jbang "$0" "$@" ; exit $?
    //DEPS info.picocli:picocli:4.6.3
    //JAVA 25+
    
    import picocli.CommandLine;
    import picocli.CommandLine.Command;
    import picocli.CommandLine.Parameters;
    
    @Command(name = "hello", mixinStandardHelpOptions = true)
    class hello implements Runnable {
        @Parameters(index = "0", description = "The greeting to print")
        private String greeting;
    
        void main(String[] args) {
            new CommandLine(new hello()).execute(args);
        }
    
        public void run() {
            System.out.println("Hello " + greeting);
        }
    }
    ///usr/bin/env jbang "$0" "$@" ; exit $?
    //DEPS info.picocli:picocli:4.6.3
    //JAVA 25+
    
    import picocli.CommandLine;
    import picocli.CommandLine.Command;
    import picocli.CommandLine.Parameters;
    
    @Command(name = "hello", mixinStandardHelpOptions = true)
    class hello implements Runnable {
        @Parameters(index = "0", description = "The greeting to print")
        private String greeting;
    
        void main(String[] args) {
            new CommandLine(new hello()).execute(args);
        }
    
        public void run() {
            System.out.println("Hello " + greeting);
        }
    }
  7. Use Sandbox mode for IDEs without JBang support

    main

    If your IDE does not have dedicated JBang support, use the sandbox mode (-b or --sandbox) with the edit command.

    In this mode, JBang generates a temporary project in a temporary location using symbolic links to your script. This allows most Java-based IDEs to treat the script as a standard project. JBang generates a build.gradle file and IDE-specific settings (currently for Eclipse and VS Code) to facilitate this.

  8. Local vs Global JBang configuration

    main

    JBang configuration can be applied at two scopes:

    1. Global Scope: Applies to all JBang runs. Defaults are stored in ~/.jbang/jbang.properties.
    2. Local Scope: Applies only within a specific directory tree. To create a local configuration, run jbang config set --file=<path> <key> <value> within that directory. This creates a local jbang.properties file that overrides global settings.

    To inspect the origin and order of your configuration settings, use jbang config list --show-origin.

  9. Syntax rules for JBang script directives

    main

    JBang uses special comments (directives) starting with // to configure compilation and execution. To ensure they are processed correctly, follow these rules:

    • Directives must start at the beginning of a line with // (no leading whitespace).
    • They must be placed in the first comment block of the file, before any actual code.
    • They are case-sensitive.
    • There must be no space between // and the directive name (e.g., use //DEPS, not // DEPS).
    • They can appear multiple times if the directive supports it (like //DEPS).
    ///usr/bin/env jbang "$0" "$@" ; exit $?
    //DEPS com.example:library:1.0.0
    //JAVA 17+
    //PREVIEW
    
    class MyScript {
        // ... your code
    }
  10. Naming conventions for JBang scripts

    main
    JBang supports any valid Java class name, including standard camel case (e.g., HelloWorld.java). However, many JBang examples use lower case names (e.g., helloworld.java) to follow the convention of command-line tools. You should choose the convention that best fits your use case.
  11. Use properties in templates

    main

    Templates can access values passed during initialization via the -Dkey=value flag. Inside the template files, these values are accessible using the \{key} syntax.

    Example: If you run jbang init -t=my-template -DmyVar=hello, you can use \{myVar} within your template files to inject the value hello.

  12. Configure HTTP Authentication for JBang

    main

    JBang uses several sources for HTTPS authentication (scripts, catalogs, and Maven repositories). The first match wins, following this order:

    1. URL userinfo: Credentials in the URL (e.g., https://user:pass@host/path). Only for HTTP downloads.
    2. .netrc exact host match: Per-host credentials in ~/.netrc.
    3. GITHUB_TOKEN: Environment variable for github.com and related hosts.
    4. GITLAB_TOKEN: Environment variable for gitlab.com and related hosts.
    5. .netrc default entry: Fallback entry in ~/.netrc.
    6. JBANG_AUTH_BASIC_USERNAME / JBANG_AUTH_BASIC_PASSWORD: Global fallback environment variables.

    Note for Maven repositories: ~/.m2/settings.xml <server> entries are also honored and take precedence over the sources above when the server <id> matches the repository ID.