blob: 84859d738ac9b2e5f08278c74330c5a2dfd88c2c [file] [log] [blame]
Bob Badourf8792242022-02-01 11:54:20 -08001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
18 "bytes"
19 "compress/gzip"
20 "encoding/xml"
21 "flag"
22 "fmt"
23 "io"
24 "io/fs"
25 "os"
26 "path/filepath"
27 "strings"
28
29 "android/soong/tools/compliance"
30
31 "github.com/google/blueprint/deptools"
32)
33
34var (
35 outputFile = flag.String("o", "-", "Where to write the NOTICE xml or xml.gz file. (default stdout)")
36 depsFile = flag.String("d", "", "Where to write the deps file")
Bob Badour49dd4f72022-02-04 14:49:01 -080037 product = flag.String("product", "", "The name of the product for which the notice is generated.")
Bob Badour682e1ba2022-02-02 15:15:56 -080038 stripPrefix = newMultiString("strip_prefix", "Prefix to remove from paths. i.e. path to root (multiple allowed)")
39 title = flag.String("title", "", "The title of the notice file.")
Bob Badourf8792242022-02-01 11:54:20 -080040
41 failNoneRequested = fmt.Errorf("\nNo license metadata files requested")
42 failNoLicenses = fmt.Errorf("No licenses found")
43)
44
45type context struct {
46 stdout io.Writer
47 stderr io.Writer
48 rootFS fs.FS
Bob Badour49dd4f72022-02-04 14:49:01 -080049 product string
Bob Badour682e1ba2022-02-02 15:15:56 -080050 stripPrefix []string
51 title string
Bob Badourf8792242022-02-01 11:54:20 -080052 deps *[]string
53}
54
Bob Badour682e1ba2022-02-02 15:15:56 -080055func (ctx context) strip(installPath string) string {
56 for _, prefix := range ctx.stripPrefix {
57 if strings.HasPrefix(installPath, prefix) {
58 p := strings.TrimPrefix(installPath, prefix)
59 if 0 == len(p) {
Bob Badour49dd4f72022-02-04 14:49:01 -080060 p = ctx.product
Bob Badour682e1ba2022-02-02 15:15:56 -080061 }
62 if 0 == len(p) {
63 continue
64 }
65 return p
66 }
67 }
68 return installPath
69}
70
Bob Badourf8792242022-02-01 11:54:20 -080071func init() {
72 flag.Usage = func() {
73 fmt.Fprintf(os.Stderr, `Usage: %s {options} file.meta_lic {file.meta_lic...}
74
75Outputs an xml NOTICE.xml or gzipped NOTICE.xml.gz file if the -o filename ends
76with ".gz".
77
78Options:
79`, filepath.Base(os.Args[0]))
80 flag.PrintDefaults()
81 }
82}
83
Bob Badour682e1ba2022-02-02 15:15:56 -080084// newMultiString creates a flag that allows multiple values in an array.
85func newMultiString(name, usage string) *multiString {
86 var f multiString
87 flag.Var(&f, name, usage)
88 return &f
89}
90
91// multiString implements the flag `Value` interface for multiple strings.
92type multiString []string
93
94func (ms *multiString) String() string { return strings.Join(*ms, ", ") }
95func (ms *multiString) Set(s string) error { *ms = append(*ms, s); return nil }
96
Bob Badourf8792242022-02-01 11:54:20 -080097func main() {
98 flag.Parse()
99
100 // Must specify at least one root target.
101 if flag.NArg() == 0 {
102 flag.Usage()
103 os.Exit(2)
104 }
105
106 if len(*outputFile) == 0 {
107 flag.Usage()
108 fmt.Fprintf(os.Stderr, "must specify file for -o; use - for stdout\n")
109 os.Exit(2)
110 } else {
111 dir, err := filepath.Abs(filepath.Dir(*outputFile))
112 if err != nil {
113 fmt.Fprintf(os.Stderr, "cannot determine path to %q: %s\n", *outputFile, err)
114 os.Exit(1)
115 }
116 fi, err := os.Stat(dir)
117 if err != nil {
118 fmt.Fprintf(os.Stderr, "cannot read directory %q of %q: %s\n", dir, *outputFile, err)
119 os.Exit(1)
120 }
121 if !fi.IsDir() {
122 fmt.Fprintf(os.Stderr, "parent %q of %q is not a directory\n", dir, *outputFile)
123 os.Exit(1)
124 }
125 }
126
127 var ofile io.Writer
128 var closer io.Closer
129 ofile = os.Stdout
130 var obuf *bytes.Buffer
131 if *outputFile != "-" {
132 obuf = &bytes.Buffer{}
133 ofile = obuf
134 }
135 if strings.HasSuffix(*outputFile, ".gz") {
136 ofile, _ = gzip.NewWriterLevel(obuf, gzip.BestCompression)
137 closer = ofile.(io.Closer)
138 }
139
140 var deps []string
141
Bob Badourc778e4c2022-03-22 13:05:19 -0700142 ctx := &context{ofile, os.Stderr, compliance.FS, *product, *stripPrefix, *title, &deps}
Bob Badourf8792242022-02-01 11:54:20 -0800143
144 err := xmlNotice(ctx, flag.Args()...)
145 if err != nil {
146 if err == failNoneRequested {
147 flag.Usage()
148 }
149 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
150 os.Exit(1)
151 }
152 if closer != nil {
153 closer.Close()
154 }
155
156 if *outputFile != "-" {
157 err := os.WriteFile(*outputFile, obuf.Bytes(), 0666)
158 if err != nil {
159 fmt.Fprintf(os.Stderr, "could not write output to %q: %s\n", *outputFile, err)
160 os.Exit(1)
161 }
162 }
163 if *depsFile != "" {
164 err := deptools.WriteDepFile(*depsFile, *outputFile, deps)
165 if err != nil {
166 fmt.Fprintf(os.Stderr, "could not write deps to %q: %s\n", *depsFile, err)
167 os.Exit(1)
168 }
169 }
170 os.Exit(0)
171}
172
173// xmlNotice implements the xmlnotice utility.
174func xmlNotice(ctx *context, files ...string) error {
175 // Must be at least one root file.
176 if len(files) < 1 {
177 return failNoneRequested
178 }
179
180 // Read the license graph from the license metadata files (*.meta_lic).
181 licenseGraph, err := compliance.ReadLicenseGraph(ctx.rootFS, ctx.stderr, files)
182 if err != nil {
183 return fmt.Errorf("Unable to read license metadata file(s) %q: %v\n", files, err)
184 }
185 if licenseGraph == nil {
186 return failNoLicenses
187 }
188
189 // rs contains all notice resolutions.
190 rs := compliance.ResolveNotices(licenseGraph)
191
192 ni, err := compliance.IndexLicenseTexts(ctx.rootFS, licenseGraph, rs)
193 if err != nil {
194 return fmt.Errorf("Unable to read license text file(s) for %q: %v\n", files, err)
195 }
196
197 fmt.Fprintln(ctx.stdout, "<?xml version=\"1.0\" encoding=\"utf-8\"?>")
198 fmt.Fprintln(ctx.stdout, "<licenses>")
199
200 for installPath := range ni.InstallPaths() {
Bob Badour682e1ba2022-02-02 15:15:56 -0800201 p := ctx.strip(installPath)
Bob Badourf8792242022-02-01 11:54:20 -0800202 for _, h := range ni.InstallHashes(installPath) {
203 for _, lib := range ni.InstallHashLibs(installPath, h) {
204 fmt.Fprintf(ctx.stdout, "<file-name contentId=\"%s\" lib=\"", h.String())
205 xml.EscapeText(ctx.stdout, []byte(lib))
206 fmt.Fprintf(ctx.stdout, "\">")
207 xml.EscapeText(ctx.stdout, []byte(p))
208 fmt.Fprintln(ctx.stdout, "</file-name>")
209 }
210 }
211 }
212 for h := range ni.Hashes() {
213 fmt.Fprintf(ctx.stdout, "<file-content contentId=\"%s\"><![CDATA[", h)
214 xml.EscapeText(ctx.stdout, ni.HashText(h))
215 fmt.Fprintf(ctx.stdout, "]]></file-content>\n\n")
216 }
217 fmt.Fprintln(ctx.stdout, "</licenses>")
218
219 *ctx.deps = ni.InputNoticeFiles()
220
221 return nil
222}