'Composer Script echo

What is the best way to echo to the console in a composer.json script? For example, I have used the scripts section to create a custom installer and at the end I want to display a message in the console.

At the moment i'm simply doing an echo like this

"scripts": {
    "post-update-cmd": [
        "clear",
        "echo \"\n\nInstallation Complete\""
    ]
}

This works, but it prints out the command and the echo in the console, so it ends up looking like this.

enter image description here

As composer outputs all of the custom commands that are in the scripts anyway, it doubles up and looks ugly!

Whats the best and cleanest way to use the composer scripts to echo a message to the console?



Solution 1:[1]

If you use a PHP class instead of using shell directly for your scripts, you can use Composers' IO system to write to the console.

For example, create a class similar to this:

<?php

declare(strict_types=1);

namespace MyApp\Composer;

use Composer\Script\Event;

class ScriptHandler
{
    public static function myScript(Event $event): void
    {
        // Your script here
    }
}

Composer\Script\Event class has a method called getIO() which you can use to get the instance of Composer\IO\IOInterface, which then has a method write, making your myScript method looking something like this:

public static function myScript(Event $event): void
{
    $event->getIO()->write('foo'):
}

Finally, to use this class, just reference it in your post-update-cmd:

"scripts": {
    "post-update-cmd": [
        "MyApp\\Composer\\ScriptHandler::myScript"
    ]
}

Solution 2:[2]

I just had to do something similar today and didn't feel like writing a whole script/class for this.

I got it working better than I expected by abusing two things:

  1. text preceded by hash marks is not executed in most consoles
  2. turns out that the script command is passed through symfony console output

So for example:

  "scripts": {
    "post-update-cmd": [
      "# <info>For your info</info>",
      "# <comment>A comment</comment>",
      "# <error>Error!!!!</error>",
      "# <href=https://symfony.com>Symfony Homepage</>"
    ]
  }

Produces:

enter image description here Tada!

Caveats:

  1. the hash mark and angle bracket will be shown anyway
  2. the command is executed anyway - terminals that do not understand the hash mark will produce weird / potentially damaging results

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Christian