blob: eb169f361ff29f2167364012dc2a4573d670b7fe [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 Badour682e1ba2022-02-02 15:15:56 -080037 stripPrefix = newMultiString("strip_prefix", "Prefix to remove from paths. i.e. path to root (multiple allowed)")
38 title = flag.String("title", "", "The title of the notice file.")
Bob Badourf8792242022-02-01 11:54:20 -080039
40 failNoneRequested = fmt.Errorf("\nNo license metadata files requested")
41 failNoLicenses = fmt.Errorf("No licenses found")
42)
43
44type context struct {
45 stdout io.Writer
46 stderr io.Writer
47 rootFS fs.FS
Bob Badour682e1ba2022-02-02 15:15:56 -080048 stripPrefix []string
49 title string
Bob Badourf8792242022-02-01 11:54:20 -080050 deps *[]string
51}
52
Bob Badour682e1ba2022-02-02 15:15:56 -080053func (ctx context) strip(installPath string) string {
54 for _, prefix := range ctx.stripPrefix {
55 if strings.HasPrefix(installPath, prefix) {
56 p := strings.TrimPrefix(installPath, prefix)
57 if 0 == len(p) {
58 p = ctx.title
59 }
60 if 0 == len(p) {
61 continue
62 }
63 return p
64 }
65 }
66 return installPath
67}
68
Bob Badourf8792242022-02-01 11:54:20 -080069func init() {
70 flag.Usage = func() {
71 fmt.Fprintf(os.Stderr, `Usage: %s {options} file.meta_lic {file.meta_lic...}
72
73Outputs an xml NOTICE.xml or gzipped NOTICE.xml.gz file if the -o filename ends
74with ".gz".
75
76Options:
77`, filepath.Base(os.Args[0]))
78 flag.PrintDefaults()
79 }
80}
81
Bob Badour682e1ba2022-02-02 15:15:56 -080082// newMultiString creates a flag that allows multiple values in an array.
83func newMultiString(name, usage string) *multiString {
84 var f multiString
85 flag.Var(&f, name, usage)
86 return &f
87}
88
89// multiString implements the flag `Value` interface for multiple strings.
90type multiString []string
91
92func (ms *multiString) String() string { return strings.Join(*ms, ", ") }
93func (ms *multiString) Set(s string) error { *ms = append(*ms, s); return nil }
94
Bob Badourf8792242022-02-01 11:54:20 -080095func main() {
96 flag.Parse()
97
98 // Must specify at least one root target.
99 if flag.NArg() == 0 {
100 flag.Usage()
101 os.Exit(2)
102 }
103
104 if len(*outputFile) == 0 {
105 flag.Usage()
106 fmt.Fprintf(os.Stderr, "must specify file for -o; use - for stdout\n")
107 os.Exit(2)
108 } else {
109 dir, err := filepath.Abs(filepath.Dir(*outputFile))
110 if err != nil {
111 fmt.Fprintf(os.Stderr, "cannot determine path to %q: %s\n", *outputFile, err)
112 os.Exit(1)
113 }
114 fi, err := os.Stat(dir)
115 if err != nil {
116 fmt.Fprintf(os.Stderr, "cannot read directory %q of %q: %s\n", dir, *outputFile, err)
117 os.Exit(1)
118 }
119 if !fi.IsDir() {
120 fmt.Fprintf(os.Stderr, "parent %q of %q is not a directory\n", dir, *outputFile)
121 os.Exit(1)
122 }
123 }
124
125 var ofile io.Writer
126 var closer io.Closer
127 ofile = os.Stdout
128 var obuf *bytes.Buffer
129 if *outputFile != "-" {
130 obuf = &bytes.Buffer{}
131 ofile = obuf
132 }
133 if strings.HasSuffix(*outputFile, ".gz") {
134 ofile, _ = gzip.NewWriterLevel(obuf, gzip.BestCompression)
135 closer = ofile.(io.Closer)
136 }
137
138 var deps []string
139
Bob Badour682e1ba2022-02-02 15:15:56 -0800140 ctx := &context{ofile, os.Stderr, os.DirFS("."), *stripPrefix, *title, &deps}
Bob Badourf8792242022-02-01 11:54:20 -0800141
142 err := xmlNotice(ctx, flag.Args()...)
143 if err != nil {
144 if err == failNoneRequested {
145 flag.Usage()
146 }
147 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
148 os.Exit(1)
149 }
150 if closer != nil {
151 closer.Close()
152 }
153
154 if *outputFile != "-" {
155 err := os.WriteFile(*outputFile, obuf.Bytes(), 0666)
156 if err != nil {
157 fmt.Fprintf(os.Stderr, "could not write output to %q: %s\n", *outputFile, err)
158 os.Exit(1)
159 }
160 }
161 if *depsFile != "" {
162 err := deptools.WriteDepFile(*depsFile, *outputFile, deps)
163 if err != nil {
164 fmt.Fprintf(os.Stderr, "could not write deps to %q: %s\n", *depsFile, err)
165 os.Exit(1)
166 }
167 }
168 os.Exit(0)
169}
170
171// xmlNotice implements the xmlnotice utility.
172func xmlNotice(ctx *context, files ...string) error {
173 // Must be at least one root file.
174 if len(files) < 1 {
175 return failNoneRequested
176 }
177
178 // Read the license graph from the license metadata files (*.meta_lic).
179 licenseGraph, err := compliance.ReadLicenseGraph(ctx.rootFS, ctx.stderr, files)
180 if err != nil {
181 return fmt.Errorf("Unable to read license metadata file(s) %q: %v\n", files, err)
182 }
183 if licenseGraph == nil {
184 return failNoLicenses
185 }
186
187 // rs contains all notice resolutions.
188 rs := compliance.ResolveNotices(licenseGraph)
189
190 ni, err := compliance.IndexLicenseTexts(ctx.rootFS, licenseGraph, rs)
191 if err != nil {
192 return fmt.Errorf("Unable to read license text file(s) for %q: %v\n", files, err)
193 }
194
195 fmt.Fprintln(ctx.stdout, "<?xml version=\"1.0\" encoding=\"utf-8\"?>")
196 fmt.Fprintln(ctx.stdout, "<licenses>")
197
198 for installPath := range ni.InstallPaths() {
Bob Badour682e1ba2022-02-02 15:15:56 -0800199 p := ctx.strip(installPath)
Bob Badourf8792242022-02-01 11:54:20 -0800200 for _, h := range ni.InstallHashes(installPath) {
201 for _, lib := range ni.InstallHashLibs(installPath, h) {
202 fmt.Fprintf(ctx.stdout, "<file-name contentId=\"%s\" lib=\"", h.String())
203 xml.EscapeText(ctx.stdout, []byte(lib))
204 fmt.Fprintf(ctx.stdout, "\">")
205 xml.EscapeText(ctx.stdout, []byte(p))
206 fmt.Fprintln(ctx.stdout, "</file-name>")
207 }
208 }
209 }
210 for h := range ni.Hashes() {
211 fmt.Fprintf(ctx.stdout, "<file-content contentId=\"%s\"><![CDATA[", h)
212 xml.EscapeText(ctx.stdout, ni.HashText(h))
213 fmt.Fprintf(ctx.stdout, "]]></file-content>\n\n")
214 }
215 fmt.Fprintln(ctx.stdout, "</licenses>")
216
217 *ctx.deps = ni.InputNoticeFiles()
218
219 return nil
220}