Skip to content

🧩 AddScript

Adds a script to the scripts section of composer.json, optionally with a description.

When to use

Use when you need to automatically run commands on lifecycle hooks such as install, update, or test. A Composer script can be a single command string, a PHP callback, or an array of commands. This method only modifies the configuration file; once registered, it can be triggered with composer run-script.

Signature

go
func (c *Composer) AddScript(name string, script interface{}, description string) error

Parameters

ParameterTypeDescription
namestringScript name, e.g. post-install-cmd or a custom name like test
scriptinterface{}Script content; can be a string, []string, or PHP callback string
descriptionstringScript description, optional; when non-empty it is written to the scripts-descriptions section

Return value

  • error: Returned when reading or writing composer.json fails.

Example

go
package main

import (
	"log"

	"github.com/scagogogo/composer-skills/pkg/composer"
)

func main() {
	comp, err := composer.New(composer.DefaultOptions())
	if err != nil {
		log.Fatal(err)
	}

	// Add a single-command script (runs after install)
	if err := comp.AddScript(
		"post-install-cmd",
		"php -r \"echo 'Installation completed!';\"",
		"Run after installation",
	); err != nil {
		log.Fatal(err)
	}

	// Add a multi-command script
	commands := []string{
		"php -r \"echo 'Starting tests...';\"",
		"phpunit",
	}
	if err := comp.AddScript("test", commands, "Run tests"); err != nil {
		log.Fatal(err)
	}
}

Advanced

  • 🔄 Internal flow: ReadComposerJSON → write Scripts[name] → optionally write ScriptsDescriptions[name]WriteComposerJSON.
  • ⚠️ If a script with the same name already exists, it is overwritten.
  • 🏃 To actually run a registered script, see RunScript / ExecuteScript; to list scripts, see ListScripts.
  • 🗑️ The corresponding removal method is RemoveScript.

Released under the MIT License