📄 ReadComposerJSON
Reads and parses the composer.json file in the working directory, returning a structured ComposerJSON object.
When to use
Use this when you need to read the project's composer.json configuration (project name, dependencies, scripts, autoload, etc.) in code for querying or modifying. This method is also the foundation of write methods such as AddRequire and SetProperty — they internally call this method first to read the existing configuration.
Signature
go
func (c *Composer) ReadComposerJSON() (*ComposerJSON, error)Parameters
| Parameter | Type | Description |
|---|---|---|
| None | — | The method reads composer.json directly from the Composer working directory (set via SetWorkingDir, or os.Getwd() if unset) |
Return value
*ComposerJSON: the parsed composer.json struct pointer, containing all fields such asName,Require,RequireDev,Scripts, andAutoload.error: returnsErrComposerJSONNotFoundwhen the file does not exist; returns the corresponding error when JSON parsing fails or reading fails.
Example
go
package main
import (
"fmt"
"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.Fatalf("failed to read composer.json: %v", err)
}
fmt.Printf("Project name: %s\n", data.Name)
fmt.Printf("Production dependency count: %d\n", len(data.Require))
for pkg, ver := range data.Require {
fmt.Printf(" %s => %s\n", pkg, ver)
}
}Advanced
- 🧪 For testing, you can inject mock data with
SetMockComposerJSONand clear it withClearMockComposerJSON, avoiding reliance on real files. - ⚠️ This method returns
ComposerJSON(a strongly typed struct); for loosermap[string]interface{}access, useReadComposerJsoninstead (see convenience.go). - ✏️ After modification, write it back to disk with
WriteComposerJSON.