Skip to content

📦 RequirePackageWithOptions Add a package dependency with custom options

🔍 RequirePackageWithOptions adds a new dependency package to the project and supports passing extra options (e.g. --dev, --prefer-source, --no-update), equivalent to running composer require [options] packageName:version.

📋 Signature

go
func (c *Composer) RequirePackageWithOptions(packageName string, version string, options map[string]string) error

📥 Parameters

ParameterTypeDescription
packageNamestringThe name of the package to add, e.g. symfony/console
versionstringVersion constraint, e.g. ^5.0; pass an empty string "" to use the latest version
optionsmap[string]stringExtra options map; keys are option names and values are option values; an empty string "" value denotes a valueless switch flag

📤 Return value

Return valueTypeDescription
First return valueerrorReturned when an error occurs during addition; nil on success

📝 Example

go
package main

import (
	"log"

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

func main() {
	comp, err := composer.NewComposer()
	if err != nil {
		log.Fatalf("failed to create Composer instance: %v", err)
	}

	// Add a development dependency and specify multiple options
	options := map[string]string{
		"dev":          "",
		"prefer-source": "",
		"no-update":    "",
	}
	if err := comp.RequirePackageWithOptions("phpunit/phpunit", "^9.0", options); err != nil {
		log.Fatalf("add dependency failed: %v", err)
	}
	log.Println("Dependency addition complete")
}

🚀 Advanced

  • 📋 If no extra options are needed, use the simpler RequirePackage(packageName, version, dev); the dev boolean is equivalent to adding "dev": "" to options.
  • 🧪 Combined with "dry-run": "", you can preview the addition result without modifying composer.json, equivalent to RequireDryRun but with more flexible options.
  • ⚙️ Common options: dev (development dependency), prefer-source/prefer-dist (installation source), no-update (only modify json without resolving dependencies), ignore-platform-reqs (ignore platform requirements).
  • 🔗 Under the hood, buildOptionsArgs(options) expands the map into command-line arguments, concatenates package:version, and then calls c.Run("require", ...); map iteration order does not affect the determinism of the final command construction.

Released under the MIT License