Skip to content

📜 许可证

列出项目所有依赖的许可证,并支持按格式输出、自定义选项与许可证兼容性检查。

Composer Skills 把 composer licenses 封装为从「原始文本」到「结构化 JSON」的多层方法。结构化方法 GetLicensesInfo 自动把 Composer 的 {"vendor/package":["MIT"]} 映射归一化为 []LicenseInfo 切片,便于遍历。

何时使用

  • ⚖️ 法务/合规审查:发布产品前确认所有依赖许可证与你的发行策略兼容(避免 GPL 误入闭源产品)。
  • 📋 生成第三方组件清单(SBOM)时附带许可证字段。
  • 🚧 CI 门禁:用 CheckLicenses 阻断引入不兼容许可证的依赖。
  • 📊 仪表盘统计项目许可证分布(MIT / Apache-2.0 / BSD 等)。

结构化类型

LicenseInfo

LicensesResult 中的元素,表示单个包的许可证信息。

go
type LicenseInfo struct {
    Package  string   `json:"package"`
    Version  string   `json:"version,omitempty"`
    Licenses []string `json:"licenses,omitempty"`
}
字段类型说明
Packagestring包名,如 symfony/console
Versionstring版本号(结构化解析时通常为空)
Licenses[]string许可证标识列表,如 ["MIT"]

LicensesResult

GetLicensesInfo 返回的顶层结果。

go
type LicensesResult struct {
    Licenses []LicenseInfo `json:"licenses,omitempty"`
}

方法签名

方法签名说明
📜 Licensesfunc (c *Composer) Licenses() (string, error)composer licenses 文本输出
🎨 LicensesWithFormatfunc (c *Composer) LicensesWithFormat(format string) (string, error)指定 --formattext/json
⚙️ LicensesWithOptionsfunc (c *Composer) LicensesWithOptions(options map[string]string) (string, error)自定义选项
✅ CheckLicensesfunc (c *Composer) CheckLicenses() (string, error)许可证兼容性检查(--check
📊 GetLicensesInfofunc (c *Composer) GetLicensesInfo() (*LicensesResult, error)结构化许可证信息

参数说明

LicensesWithFormat

参数类型说明
formatstring输出格式,textjson

示例

结构化获取所有依赖许可证

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.Fatalf("初始化失败: %v", err)
	}

	result, err := comp.GetLicensesInfo()
	if err != nil {
		log.Fatalf("获取许可证信息失败: %v", err)
	}

	for _, li := range result.Licenses {
		fmt.Printf("%-30s %v\n", li.Package, li.Licenses)
	}
}

统计许可证分布

go
result, _ := comp.GetLicensesInfo()
dist := map[string]int{}
for _, li := range result.Licenses {
	for _, lic := range li.Licenses {
		dist[lic]++
	}
}
for lic, n := range dist {
	fmt.Printf("%-15s %d 个包\n", lic, n)
}

CI 门禁:检查许可证兼容性

go
out, err := comp.CheckLicenses()
if err != nil {
	log.Fatalf("许可证检查未通过: %v\n%s", err, out)
}
fmt.Println("✅ 许可证兼容性检查通过")

指定 JSON 格式

go
out, err := comp.LicensesWithFormat("json")
if err != nil {
	log.Fatal(err)
}
fmt.Println(out)

自定义选项

go
out, err := comp.LicensesWithOptions(map[string]string{
	"format": "json",
	"no-dev": "",
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(out)

进阶

GetLicensesInfo 的归一化

Composer licenses --format=json 原始输出是 {"vendor/package":["MIT"]} 的映射。ParseLicensesResult 把它转成 []LicenseInfo,每个包对应一条记录,方便遍历与序列化。

CheckLicenses 依赖 composer.json 配置

composer licenses --check 需要在 composer.jsonconfig.allow-list / config.filed-license 中预先声明允许的许可证,否则检查无意义。本方法只负责执行命令,不替你定义策略。

基于 MIT 许可证发布