blob: 5770a7fff3887c73cf18706cd3eb6fb77a50ebb0 [file] [log] [blame]
Colin Cross70dd38f2018-04-16 13:52:10 -07001// Copyright 2017 Google Inc. All rights reserved.
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 (
Colin Crosscf53e602018-06-26 15:27:20 -070018 "archive/zip"
Colin Cross70dd38f2018-04-16 13:52:10 -070019 "bufio"
20 "bytes"
21 "encoding/xml"
22 "flag"
23 "fmt"
24 "io/ioutil"
25 "os"
26 "os/exec"
27 "path/filepath"
28 "regexp"
29 "sort"
30 "strings"
31 "text/template"
32
33 "github.com/google/blueprint/proptools"
34
35 "android/soong/bpfix/bpfix"
36)
37
38type RewriteNames []RewriteName
39type RewriteName struct {
40 regexp *regexp.Regexp
41 repl string
42}
43
44func (r *RewriteNames) String() string {
45 return ""
46}
47
48func (r *RewriteNames) Set(v string) error {
49 split := strings.SplitN(v, "=", 2)
50 if len(split) != 2 {
51 return fmt.Errorf("Must be in the form of <regex>=<replace>")
52 }
53 regex, err := regexp.Compile(split[0])
54 if err != nil {
55 return nil
56 }
57 *r = append(*r, RewriteName{
58 regexp: regex,
59 repl: split[1],
60 })
61 return nil
62}
63
64func (r *RewriteNames) MavenToBp(groupId string, artifactId string) string {
65 for _, r := range *r {
66 if r.regexp.MatchString(groupId + ":" + artifactId) {
67 return r.regexp.ReplaceAllString(groupId+":"+artifactId, r.repl)
68 } else if r.regexp.MatchString(artifactId) {
69 return r.regexp.ReplaceAllString(artifactId, r.repl)
70 }
71 }
72 return artifactId
73}
74
75var rewriteNames = RewriteNames{}
76
77type ExtraDeps map[string][]string
78
79func (d ExtraDeps) String() string {
80 return ""
81}
82
83func (d ExtraDeps) Set(v string) error {
84 split := strings.SplitN(v, "=", 2)
85 if len(split) != 2 {
86 return fmt.Errorf("Must be in the form of <module>=<module>[,<module>]")
87 }
88 d[split[0]] = strings.Split(split[1], ",")
89 return nil
90}
91
Paul Duffinbabaf072019-04-16 11:35:20 +010092var extraStaticLibs = make(ExtraDeps)
93
94var extraLibs = make(ExtraDeps)
Colin Cross70dd38f2018-04-16 13:52:10 -070095
Alan Viverette24658d02021-08-31 20:00:52 +000096var optionalUsesLibs = make(ExtraDeps)
97
Colin Cross70dd38f2018-04-16 13:52:10 -070098type Exclude map[string]bool
99
100func (e Exclude) String() string {
101 return ""
102}
103
104func (e Exclude) Set(v string) error {
105 e[v] = true
106 return nil
107}
108
109var excludes = make(Exclude)
110
Jeff Gastond4928532018-08-24 14:30:13 -0400111type HostModuleNames map[string]bool
112
113func (n HostModuleNames) IsHostModule(groupId string, artifactId string) bool {
Colin Cross86bc9d42018-08-29 15:36:33 -0700114 _, found := n[groupId+":"+artifactId]
Jeff Gastond4928532018-08-24 14:30:13 -0400115 return found
116}
117
118func (n HostModuleNames) String() string {
119 return ""
120}
121
122func (n HostModuleNames) Set(v string) error {
123 n[v] = true
124 return nil
125}
126
127var hostModuleNames = HostModuleNames{}
128
Tony Mak81785002019-07-18 21:36:44 +0100129type HostAndDeviceModuleNames map[string]bool
130
131func (n HostAndDeviceModuleNames) IsHostAndDeviceModule(groupId string, artifactId string) bool {
132 _, found := n[groupId+":"+artifactId]
133
134 return found
135}
136
137func (n HostAndDeviceModuleNames) String() string {
138 return ""
139}
140
141func (n HostAndDeviceModuleNames) Set(v string) error {
142 n[v] = true
143 return nil
144}
145
146var hostAndDeviceModuleNames = HostAndDeviceModuleNames{}
147
Colin Cross70dd38f2018-04-16 13:52:10 -0700148var sdkVersion string
Anton Hanssonc29f0762021-03-29 16:10:06 +0100149var defaultMinSdkVersion string
Colin Cross70dd38f2018-04-16 13:52:10 -0700150var useVersion string
Dan Willemsen52c90d82019-04-21 21:37:39 -0700151var staticDeps bool
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700152var jetifier bool
Colin Cross70dd38f2018-04-16 13:52:10 -0700153
154func InList(s string, list []string) bool {
155 for _, l := range list {
156 if l == s {
157 return true
158 }
159 }
160
161 return false
162}
163
164type Dependency struct {
165 XMLName xml.Name `xml:"dependency"`
166
167 BpTarget string `xml:"-"`
168
169 GroupId string `xml:"groupId"`
170 ArtifactId string `xml:"artifactId"`
171 Version string `xml:"version"`
172 Type string `xml:"type"`
173 Scope string `xml:"scope"`
174}
175
176func (d Dependency) BpName() string {
177 if d.BpTarget == "" {
178 d.BpTarget = rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
179 }
180 return d.BpTarget
181}
182
183type Pom struct {
184 XMLName xml.Name `xml:"http://maven.apache.org/POM/4.0.0 project"`
185
Colin Crosscf53e602018-06-26 15:27:20 -0700186 PomFile string `xml:"-"`
187 ArtifactFile string `xml:"-"`
188 BpTarget string `xml:"-"`
189 MinSdkVersion string `xml:"-"`
Colin Cross70dd38f2018-04-16 13:52:10 -0700190
191 GroupId string `xml:"groupId"`
192 ArtifactId string `xml:"artifactId"`
193 Version string `xml:"version"`
194 Packaging string `xml:"packaging"`
195
196 Dependencies []*Dependency `xml:"dependencies>dependency"`
197}
198
199func (p Pom) IsAar() bool {
200 return p.Packaging == "aar"
201}
202
203func (p Pom) IsJar() bool {
204 return p.Packaging == "jar"
205}
206
Jeff Gastond4928532018-08-24 14:30:13 -0400207func (p Pom) IsHostModule() bool {
208 return hostModuleNames.IsHostModule(p.GroupId, p.ArtifactId)
209}
210
211func (p Pom) IsDeviceModule() bool {
212 return !p.IsHostModule()
213}
214
Tony Mak81785002019-07-18 21:36:44 +0100215func (p Pom) IsHostAndDeviceModule() bool {
216 return hostAndDeviceModuleNames.IsHostAndDeviceModule(p.GroupId, p.ArtifactId)
217}
218
Jooyung Han43d30252020-05-22 03:54:24 +0900219func (p Pom) IsHostOnly() bool {
220 return p.IsHostModule() && !p.IsHostAndDeviceModule()
221}
222
Colin Cross632987a2018-08-29 16:17:55 -0700223func (p Pom) ModuleType() string {
224 if p.IsAar() {
225 return "android_library"
Jooyung Han43d30252020-05-22 03:54:24 +0900226 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700227 return "java_library_host"
228 } else {
229 return "java_library_static"
230 }
231}
232
233func (p Pom) ImportModuleType() string {
234 if p.IsAar() {
235 return "android_library_import"
Jooyung Han43d30252020-05-22 03:54:24 +0900236 } else if p.IsHostOnly() {
Colin Cross632987a2018-08-29 16:17:55 -0700237 return "java_import_host"
238 } else {
239 return "java_import"
240 }
241}
242
243func (p Pom) ImportProperty() string {
244 if p.IsAar() {
245 return "aars"
246 } else {
247 return "jars"
248 }
249}
250
Colin Cross70dd38f2018-04-16 13:52:10 -0700251func (p Pom) BpName() string {
252 if p.BpTarget == "" {
253 p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
254 }
255 return p.BpTarget
256}
257
258func (p Pom) BpJarDeps() []string {
259 return p.BpDeps("jar", []string{"compile", "runtime"})
260}
261
262func (p Pom) BpAarDeps() []string {
263 return p.BpDeps("aar", []string{"compile", "runtime"})
264}
265
Paul Duffinbabaf072019-04-16 11:35:20 +0100266func (p Pom) BpExtraStaticLibs() []string {
267 return extraStaticLibs[p.BpName()]
268}
269
270func (p Pom) BpExtraLibs() []string {
271 return extraLibs[p.BpName()]
Colin Cross70dd38f2018-04-16 13:52:10 -0700272}
273
Alan Viverette24658d02021-08-31 20:00:52 +0000274func (p Pom) BpOptionalUsesLibs() []string {
275 return optionalUsesLibs[p.BpName()]
276}
277
Colin Cross70dd38f2018-04-16 13:52:10 -0700278// BpDeps obtains dependencies filtered by type and scope. The results of this
279// method are formatted as Android.bp targets, e.g. run through MavenToBp rules.
280func (p Pom) BpDeps(typeExt string, scopes []string) []string {
281 var ret []string
282 for _, d := range p.Dependencies {
283 if d.Type != typeExt || !InList(d.Scope, scopes) {
284 continue
285 }
286 name := rewriteNames.MavenToBp(d.GroupId, d.ArtifactId)
287 ret = append(ret, name)
288 }
289 return ret
290}
291
292func (p Pom) SdkVersion() string {
293 return sdkVersion
294}
295
Anton Hanssonc29f0762021-03-29 16:10:06 +0100296func (p Pom) DefaultMinSdkVersion() string {
297 return defaultMinSdkVersion
298}
299
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700300func (p Pom) Jetifier() bool {
301 return jetifier
302}
303
Colin Cross70dd38f2018-04-16 13:52:10 -0700304func (p *Pom) FixDeps(modules map[string]*Pom) {
305 for _, d := range p.Dependencies {
306 if d.Type == "" {
307 if depPom, ok := modules[d.BpName()]; ok {
308 // We've seen the POM for this dependency, use its packaging
309 // as the dependency type rather than Maven spec default.
310 d.Type = depPom.Packaging
311 } else {
312 // Dependency type was not specified and we don't have the POM
313 // for this artifact, use the default from Maven spec.
314 d.Type = "jar"
315 }
316 }
317 if d.Scope == "" {
318 // Scope was not specified, use the default from Maven spec.
319 d.Scope = "compile"
320 }
321 }
322}
323
Colin Crosscf53e602018-06-26 15:27:20 -0700324// ExtractMinSdkVersion extracts the minSdkVersion from the AndroidManifest.xml file inside an aar file, or sets it
325// to "current" if it is not present.
326func (p *Pom) ExtractMinSdkVersion() error {
327 aar, err := zip.OpenReader(p.ArtifactFile)
328 if err != nil {
329 return err
330 }
331 defer aar.Close()
332
333 var manifest *zip.File
334 for _, f := range aar.File {
335 if f.Name == "AndroidManifest.xml" {
336 manifest = f
337 break
338 }
339 }
340
341 if manifest == nil {
342 return fmt.Errorf("failed to find AndroidManifest.xml in %s", p.ArtifactFile)
343 }
344
345 r, err := manifest.Open()
346 if err != nil {
347 return err
348 }
349 defer r.Close()
350
351 decoder := xml.NewDecoder(r)
352
353 manifestData := struct {
354 XMLName xml.Name `xml:"manifest"`
355 Uses_sdk struct {
356 MinSdkVersion string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
357 } `xml:"uses-sdk"`
358 }{}
359
360 err = decoder.Decode(&manifestData)
361 if err != nil {
362 return err
363 }
364
365 p.MinSdkVersion = manifestData.Uses_sdk.MinSdkVersion
366 if p.MinSdkVersion == "" {
367 p.MinSdkVersion = "current"
368 }
369
370 return nil
371}
372
Colin Cross70dd38f2018-04-16 13:52:10 -0700373var bpTemplate = template.Must(template.New("bp").Parse(`
Colin Cross632987a2018-08-29 16:17:55 -0700374{{.ImportModuleType}} {
Dan Willemsen52c90d82019-04-21 21:37:39 -0700375 name: "{{.BpName}}",
376 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
377 sdk_version: "{{.SdkVersion}}",
378 {{- if .Jetifier}}
379 jetifier: true,
380 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100381 {{- if .IsHostAndDeviceModule}}
382 host_supported: true,
383 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900384 {{- if not .IsHostOnly}}
385 apex_available: [
386 "//apex_available:platform",
387 "//apex_available:anyapex",
388 ],
389 {{- end}}
Dan Willemsen52c90d82019-04-21 21:37:39 -0700390 {{- if .IsAar}}
391 min_sdk_version: "{{.MinSdkVersion}}",
392 static_libs: [
393 {{- range .BpJarDeps}}
394 "{{.}}",
395 {{- end}}
396 {{- range .BpAarDeps}}
397 "{{.}}",
398 {{- end}}
399 {{- range .BpExtraStaticLibs}}
400 "{{.}}",
401 {{- end}}
402 ],
403 {{- if .BpExtraLibs}}
404 libs: [
405 {{- range .BpExtraLibs}}
406 "{{.}}",
407 {{- end}}
408 ],
Alan Viverette24658d02021-08-31 20:00:52 +0000409 {{- if .BpOptionalUsesLibs}}
410 optional_uses_libs: [
411 {{- range .BpOptionalUsesLibs}}
412 "{{.}}",
413 {{- end}}
414 ],
Dan Willemsen52c90d82019-04-21 21:37:39 -0700415 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000416 {{- else if not .IsHostOnly}}
417 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Dan Willemsen52c90d82019-04-21 21:37:39 -0700418 {{- end}}
419}
420`))
421
422var bpDepsTemplate = template.Must(template.New("bp").Parse(`
423{{.ImportModuleType}} {
Colin Cross70dd38f2018-04-16 13:52:10 -0700424 name: "{{.BpName}}-nodeps",
Colin Cross632987a2018-08-29 16:17:55 -0700425 {{.ImportProperty}}: ["{{.ArtifactFile}}"],
426 sdk_version: "{{.SdkVersion}}",
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700427 {{- if .Jetifier}}
428 jetifier: true,
429 {{- end}}
Tony Mak81785002019-07-18 21:36:44 +0100430 {{- if .IsHostAndDeviceModule}}
431 host_supported: true,
432 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900433 {{- if not .IsHostOnly}}
434 apex_available: [
435 "//apex_available:platform",
436 "//apex_available:anyapex",
437 ],
438 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700439 {{- if .IsAar}}
Colin Crosscf53e602018-06-26 15:27:20 -0700440 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700441 static_libs: [
Colin Cross1aa7f262019-04-10 11:07:15 -0700442 {{- range .BpJarDeps}}
443 "{{.}}",
444 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700445 {{- range .BpAarDeps}}
446 "{{.}}",
447 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100448 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700449 "{{.}}",
450 {{- end}}
451 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100452 {{- if .BpExtraLibs}}
453 libs: [
454 {{- range .BpExtraLibs}}
455 "{{.}}",
456 {{- end}}
457 ],
Alan Viverette24658d02021-08-31 20:00:52 +0000458 {{- if .BpOptionalUsesLibs}}
459 optional_uses_libs: [
460 {{- range .BpOptionalUsesLibs}}
461 "{{.}}",
462 {{- end}}
463 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100464 {{- end}}
Anton Hanssonebfbad22021-04-06 19:21:34 +0000465 {{- else if not .IsHostOnly}}
466 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700467 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700468}
469
Colin Cross632987a2018-08-29 16:17:55 -0700470{{.ModuleType}} {
471 name: "{{.BpName}}",
472 {{- if .IsDeviceModule}}
473 sdk_version: "{{.SdkVersion}}",
Tony Mak81785002019-07-18 21:36:44 +0100474 {{- if .IsHostAndDeviceModule}}
475 host_supported: true,
476 {{- end}}
Jooyung Han43d30252020-05-22 03:54:24 +0900477 {{- if not .IsHostOnly}}
478 apex_available: [
479 "//apex_available:platform",
480 "//apex_available:anyapex",
481 ],
482 {{- end}}
Colin Cross632987a2018-08-29 16:17:55 -0700483 {{- if .IsAar}}
Colin Cross461ba492018-07-10 13:45:30 -0700484 min_sdk_version: "{{.MinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700485 manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
Jooyung Han43d30252020-05-22 03:54:24 +0900486 {{- else if not .IsHostOnly}}
Anton Hanssonc29f0762021-03-29 16:10:06 +0100487 min_sdk_version: "{{.DefaultMinSdkVersion}}",
Colin Cross632987a2018-08-29 16:17:55 -0700488 {{- end}}
489 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700490 static_libs: [
Colin Cross632987a2018-08-29 16:17:55 -0700491 "{{.BpName}}-nodeps",
Colin Cross1aa7f262019-04-10 11:07:15 -0700492 {{- range .BpJarDeps}}
Colin Cross632987a2018-08-29 16:17:55 -0700493 "{{.}}",
494 {{- end}}
495 {{- range .BpAarDeps}}
496 "{{.}}",
497 {{- end}}
Paul Duffinbabaf072019-04-16 11:35:20 +0100498 {{- range .BpExtraStaticLibs}}
Colin Cross632987a2018-08-29 16:17:55 -0700499 "{{.}}",
500 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700501 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100502 {{- if .BpExtraLibs}}
503 libs: [
504 {{- range .BpExtraLibs}}
505 "{{.}}",
506 {{- end}}
507 ],
Alan Viverette24658d02021-08-31 20:00:52 +0000508 {{- if .BpOptionalUsesLibs}}
509 optional_uses_libs: [
510 {{- range .BpOptionalUsesLibs}}
511 "{{.}}",
512 {{- end}}
513 ],
Paul Duffinbabaf072019-04-16 11:35:20 +0100514 {{- end}}
Colin Cross70dd38f2018-04-16 13:52:10 -0700515 java_version: "1.7",
516}
517`))
518
519func parse(filename string) (*Pom, error) {
520 data, err := ioutil.ReadFile(filename)
521 if err != nil {
522 return nil, err
523 }
524
525 var pom Pom
526 err = xml.Unmarshal(data, &pom)
527 if err != nil {
528 return nil, err
529 }
530
531 if useVersion != "" && pom.Version != useVersion {
532 return nil, nil
533 }
534
535 if pom.Packaging == "" {
536 pom.Packaging = "jar"
537 }
538
539 pom.PomFile = filename
540 pom.ArtifactFile = strings.TrimSuffix(filename, ".pom") + "." + pom.Packaging
541
542 return &pom, nil
543}
544
545func rerunForRegen(filename string) error {
546 buf, err := ioutil.ReadFile(filename)
547 if err != nil {
548 return err
549 }
550
551 scanner := bufio.NewScanner(bytes.NewBuffer(buf))
552
553 // Skip the first line in the file
554 for i := 0; i < 2; i++ {
555 if !scanner.Scan() {
556 if scanner.Err() != nil {
557 return scanner.Err()
558 } else {
559 return fmt.Errorf("unexpected EOF")
560 }
561 }
562 }
563
564 // Extract the old args from the file
565 line := scanner.Text()
566 if strings.HasPrefix(line, "// pom2bp ") {
567 line = strings.TrimPrefix(line, "// pom2bp ")
568 } else if strings.HasPrefix(line, "// pom2mk ") {
569 line = strings.TrimPrefix(line, "// pom2mk ")
570 } else if strings.HasPrefix(line, "# pom2mk ") {
571 line = strings.TrimPrefix(line, "# pom2mk ")
572 } else {
573 return fmt.Errorf("unexpected second line: %q", line)
574 }
575 args := strings.Split(line, " ")
576 lastArg := args[len(args)-1]
577 args = args[:len(args)-1]
578
579 // Append all current command line args except -regen <file> to the ones from the file
580 for i := 1; i < len(os.Args); i++ {
Colin Crosscf53e602018-06-26 15:27:20 -0700581 if os.Args[i] == "-regen" || os.Args[i] == "--regen" {
Colin Cross70dd38f2018-04-16 13:52:10 -0700582 i++
583 } else {
584 args = append(args, os.Args[i])
585 }
586 }
587 args = append(args, lastArg)
588
589 cmd := os.Args[0] + " " + strings.Join(args, " ")
590 // Re-exec pom2bp with the new arguments
591 output, err := exec.Command("/bin/sh", "-c", cmd).Output()
592 if exitErr, _ := err.(*exec.ExitError); exitErr != nil {
593 return fmt.Errorf("failed to run %s\n%s", cmd, string(exitErr.Stderr))
594 } else if err != nil {
595 return err
596 }
597
598 // If the old file was a .mk file, replace it with a .bp file
599 if filepath.Ext(filename) == ".mk" {
600 os.Remove(filename)
601 filename = strings.TrimSuffix(filename, ".mk") + ".bp"
602 }
603
604 return ioutil.WriteFile(filename, output, 0666)
605}
606
607func main() {
608 flag.Usage = func() {
609 fmt.Fprintf(os.Stderr, `pom2bp, a tool to create Android.bp files from maven repos
610
611The tool will extract the necessary information from *.pom files to create an Android.bp whose
612aar libraries can be linked against when using AAPT2.
613
Alan Viverette24658d02021-08-31 20:00:52 +0000614Usage: %s [--rewrite <regex>=<replace>] [--exclude <module>] [--extra-static-libs <module>=<module>[,<module>]] [--extra-libs <module>=<module>[,<module>]] [--optional-uses-libs <module>=<module>[,<module>]] [<dir>] [-regen <file>]
Colin Cross70dd38f2018-04-16 13:52:10 -0700615
616 -rewrite <regex>=<replace>
617 rewrite can be used to specify mappings between Maven projects and Android.bp modules. The -rewrite
618 option can be specified multiple times. When determining the Android.bp module for a given Maven
619 project, mappings are searched in the order they were specified. The first <regex> matching
620 either the Maven project's <groupId>:<artifactId> or <artifactId> will be used to generate
621 the Android.bp module name using <replace>. If no matches are found, <artifactId> is used.
622 -exclude <module>
623 Don't put the specified module in the Android.bp file.
Paul Duffinbabaf072019-04-16 11:35:20 +0100624 -extra-static-libs <module>=<module>[,<module>]
625 Some Android.bp modules have transitive static dependencies that must be specified when they
626 are depended upon (like android-support-v7-mediarouter requires android-support-v7-appcompat).
627 This may be specified multiple times to declare these dependencies.
628 -extra-libs <module>=<module>[,<module>]
629 Some Android.bp modules have transitive runtime dependencies that must be specified when they
630 are depended upon (like androidx.test.rules requires android.test.base).
Colin Cross70dd38f2018-04-16 13:52:10 -0700631 This may be specified multiple times to declare these dependencies.
Alan Viverette24658d02021-08-31 20:00:52 +0000632 -optional-uses-libs <module>=<module>[,<module>]
633 Some Android.bp modules have optional dependencies (typically specified with <uses-library> in
634 the module's AndroidManifest.xml) that must be specified when they are depended upon (like
635 androidx.window:window optionally requires androidx.window:window-extensions).
636 This may be specified multiple times to declare these dependencies.
Colin Cross70dd38f2018-04-16 13:52:10 -0700637 -sdk-version <version>
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700638 Sets sdk_version: "<version>" for all modules.
Anton Hanssonc29f0762021-03-29 16:10:06 +0100639 -default-min-sdk-version
640 The default min_sdk_version to use for a module if one cannot be mined from AndroidManifest.xml
Colin Cross70dd38f2018-04-16 13:52:10 -0700641 -use-version <version>
642 If the maven directory contains multiple versions of artifacts and their pom files,
643 -use-version can be used to only write Android.bp files for a specific version of those artifacts.
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700644 -jetifier
645 Sets jetifier: true for all modules.
Colin Cross70dd38f2018-04-16 13:52:10 -0700646 <dir>
647 The directory to search for *.pom files under.
648 The contents are written to stdout, to be put in the current directory (often as Android.bp)
649 -regen <file>
650 Read arguments from <file> and overwrite it (if it ends with .bp) or move it to .bp (if it
651 ends with .mk).
652
653`, os.Args[0])
654 }
655
656 var regen string
657
658 flag.Var(&excludes, "exclude", "Exclude module")
Paul Duffinbabaf072019-04-16 11:35:20 +0100659 flag.Var(&extraStaticLibs, "extra-static-libs", "Extra static dependencies needed when depending on a module")
660 flag.Var(&extraLibs, "extra-libs", "Extra runtime dependencies needed when depending on a module")
Alan Viverette24658d02021-08-31 20:00:52 +0000661 flag.Var(&optionalUsesLibs, "optional-uses-libs", "Extra optional dependencies needed when depending on a module")
Colin Cross70dd38f2018-04-16 13:52:10 -0700662 flag.Var(&rewriteNames, "rewrite", "Regex(es) to rewrite artifact names")
Jeff Gastond4928532018-08-24 14:30:13 -0400663 flag.Var(&hostModuleNames, "host", "Specifies that the corresponding module (specified in the form 'module.group:module.artifact') is a host module")
Tony Mak81785002019-07-18 21:36:44 +0100664 flag.Var(&hostAndDeviceModuleNames, "host-and-device", "Specifies that the corresponding module (specified in the form 'module.group:module.artifact') is both a host and device module.")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700665 flag.StringVar(&sdkVersion, "sdk-version", "", "What to write to sdk_version")
Anton Hanssonc29f0762021-03-29 16:10:06 +0100666 flag.StringVar(&defaultMinSdkVersion, "default-min-sdk-version", "24", "Default min_sdk_version to use, if one is not available from AndroidManifest.xml. Default: 24")
Colin Cross70dd38f2018-04-16 13:52:10 -0700667 flag.StringVar(&useVersion, "use-version", "", "Only read artifacts of a specific version")
Dan Willemsen52c90d82019-04-21 21:37:39 -0700668 flag.BoolVar(&staticDeps, "static-deps", false, "Statically include direct dependencies")
Dan Willemsen7fdab6e2019-04-20 21:47:14 -0700669 flag.BoolVar(&jetifier, "jetifier", false, "Sets jetifier: true on all modules")
Colin Cross70dd38f2018-04-16 13:52:10 -0700670 flag.StringVar(&regen, "regen", "", "Rewrite specified file")
671 flag.Parse()
672
673 if regen != "" {
674 err := rerunForRegen(regen)
675 if err != nil {
676 fmt.Fprintln(os.Stderr, err)
677 os.Exit(1)
678 }
679 os.Exit(0)
680 }
681
682 if flag.NArg() == 0 {
683 fmt.Fprintln(os.Stderr, "Directory argument is required")
684 os.Exit(1)
685 } else if flag.NArg() > 1 {
686 fmt.Fprintln(os.Stderr, "Multiple directories provided:", strings.Join(flag.Args(), " "))
687 os.Exit(1)
688 }
689
690 dir := flag.Arg(0)
691 absDir, err := filepath.Abs(dir)
692 if err != nil {
693 fmt.Fprintln(os.Stderr, "Failed to get absolute directory:", err)
694 os.Exit(1)
695 }
696
697 var filenames []string
698 err = filepath.Walk(absDir, func(path string, info os.FileInfo, err error) error {
699 if err != nil {
700 return err
701 }
702
703 name := info.Name()
704 if info.IsDir() {
705 if strings.HasPrefix(name, ".") {
706 return filepath.SkipDir
707 }
708 return nil
709 }
710
711 if strings.HasPrefix(name, ".") {
712 return nil
713 }
714
715 if strings.HasSuffix(name, ".pom") {
716 path, err = filepath.Rel(absDir, path)
717 if err != nil {
718 return err
719 }
720 filenames = append(filenames, filepath.Join(dir, path))
721 }
722 return nil
723 })
724 if err != nil {
725 fmt.Fprintln(os.Stderr, "Error walking files:", err)
726 os.Exit(1)
727 }
728
729 if len(filenames) == 0 {
730 fmt.Fprintln(os.Stderr, "Error: no *.pom files found under", dir)
731 os.Exit(1)
732 }
733
734 sort.Strings(filenames)
735
736 poms := []*Pom{}
737 modules := make(map[string]*Pom)
738 duplicate := false
739 for _, filename := range filenames {
740 pom, err := parse(filename)
741 if err != nil {
742 fmt.Fprintln(os.Stderr, "Error converting", filename, err)
743 os.Exit(1)
744 }
745
746 if pom != nil {
747 key := pom.BpName()
748 if excludes[key] {
749 continue
750 }
751
752 if old, ok := modules[key]; ok {
753 fmt.Fprintln(os.Stderr, "Module", key, "defined twice:", old.PomFile, pom.PomFile)
754 duplicate = true
755 }
756
757 poms = append(poms, pom)
758 modules[key] = pom
759 }
760 }
761 if duplicate {
762 os.Exit(1)
763 }
764
765 for _, pom := range poms {
Colin Crosscf53e602018-06-26 15:27:20 -0700766 if pom.IsAar() {
767 err := pom.ExtractMinSdkVersion()
768 if err != nil {
Colin Crossfe5a3b72018-07-13 21:25:15 -0700769 fmt.Fprintf(os.Stderr, "Error reading manifest for %s: %s", pom.ArtifactFile, err)
Colin Crosscf53e602018-06-26 15:27:20 -0700770 os.Exit(1)
771 }
772 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700773 pom.FixDeps(modules)
774 }
775
776 buf := &bytes.Buffer{}
777
778 fmt.Fprintln(buf, "// Automatically generated with:")
Colin Cross0b9f31f2019-02-28 11:00:01 -0800779 fmt.Fprintln(buf, "// pom2bp", strings.Join(proptools.ShellEscapeList(os.Args[1:]), " "))
Colin Cross70dd38f2018-04-16 13:52:10 -0700780
781 for _, pom := range poms {
782 var err error
Dan Willemsen52c90d82019-04-21 21:37:39 -0700783 if staticDeps {
784 err = bpDepsTemplate.Execute(buf, pom)
785 } else {
786 err = bpTemplate.Execute(buf, pom)
787 }
Colin Cross70dd38f2018-04-16 13:52:10 -0700788 if err != nil {
789 fmt.Fprintln(os.Stderr, "Error writing", pom.PomFile, pom.BpName(), err)
790 os.Exit(1)
791 }
792 }
793
794 out, err := bpfix.Reformat(buf.String())
795 if err != nil {
796 fmt.Fprintln(os.Stderr, "Error formatting output", err)
797 os.Exit(1)
798 }
799
800 os.Stdout.WriteString(out)
801}