✍️ WriteComposerJSON
Serializes a ComposerJSON struct into indented JSON and writes it back to the composer.json file in the working directory.
When to use
Use this when you have modified the struct fields of composer.json through code (e.g. directly editing Require, Scripts, and other maps) and need to persist the changes to disk. This method is typically paired with ReadComposerJSON: read first, modify the in-memory object, then write back.
Signature
go
func (c *Composer) WriteComposerJSON(composerJSON *ComposerJSON) errorParameters
| Parameter | Type | Description |
|---|---|---|
composerJSON | *ComposerJSON | Pointer to the composer.json struct to write |
Return value
error: returned when serialization or file writing fails;nilon success.
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)
}
data, err := comp.ReadComposerJSON()
if err != nil {
log.Fatal(err)
}
// Modify the project description
data.Description = "An even better PHP library"
if err := comp.WriteComposerJSON(data); err != nil {
log.Fatalf("write composer.json failed: %v", err)
}
}Advanced
- 📝 Writing uses
json.MarshalIndentwith 4-space indentation; the file permission is0644. - ⚠️ This method overwrites
composer.jsonin full; custom fields not mapped in the struct will be lost. To preserve unknown fields, operate on the raw file directly or use a more permissivemap[string]interface{}. - 🔗 Common write wrappers:
AddRequire,RemoveRequire,AddScript,SetProperty.