ballerina

In the Ballerina Language how do I hot reload code via `bal run` without a server restart?


I can run a development server locally via bal run and interact with my API via Swagger in VSCode (very nice!), however, it seems that I have to kill & restart the server to reflect code changes?

Is there a smarter way to automatically hot reload code changes & update the server?

I first-off expected the default behaviour to reflect code changes.

I then figured I could opt in via an option to bal run, but looking at bal run --help I didn't see any --debug or similar option?


Solution

  • Currently, there is no official support for this. But I sometimes use a shell script to do this.

    #!/bin/bash
    
    DIRECTORY_TO_WATCH="<package-directory>"    # provide the absolute directory
    
    run_command() {
        # Get the previous jvm PID and kill it
        prevJPID=$(jps | grep '$_init' | awk '{print $1}')
        kill -9 $prevJPID >/dev/null 2>&1
        wait $prevJPID 2>/dev/null
    
        # Run the command in the background and get its PID and Jvm PID
        bal run $DIRECTORY_TO_WATCH &
        PID=$!
        sleep 2
        JPID=$(jps | grep '$_init' | awk '{print $1}')
        echo "PID of the command: $PID"
        echo "PID of jvm process: $JPID"
    }
    
    run_command
    
    fswatch -0 $DIRECTORY_TO_WATCH | while IFS= read -r -d "" file; do
        if [[ "$file" == *.bal ]]; then
            echo "File changed $file"
            kill -9 $PID >/dev/null 2>&1
            wait $PID 2>/dev/null
            run_command
        fi
    done
    

    Here, you have to provide the absolute path for the DIRECTORY_TO_WATCH (e.g. "/Users/dulaj/Desktop/temp/servo").

    Also, you have to give +x permission to the file. via the following command.

    chmod +x <script-name>